Skip to Content
JavaScript 設計模式
book

JavaScript 設計模式

by Stoyan Stefanov
March 2012
Intermediate to advanced
244 pages
4h 42m
Chinese
GoTop Information, Inc.
Content preview from JavaScript 設計模式
214
   
第八章
預先載入
在延遲和隨選載入模式中,我們延後載入當前頁面所需的 script。除此之外,你也可以在
之後載入當前頁面還不需要的 script,但在新頁面很可能要出來之前載入。用這種方式,
當使用者來到第二個頁面,使用者就已經有預先下載的 script,於是整體的感覺就變得快
上許多。
預先載入可以簡單的使用動態
script
模式來實作,但這表示 script 下載後就會被分析且
執行。雖然分析只是增加了預先讀取的時間,但執行可能會額外導致 JavaScript 錯誤,
因為預先載入的 script 可能會假設它正運行在第二個頁面上,例如,預期可以找到某個
DOM 節點,但實際上不存在。
下載了 script 卻不分析與執行是有可能的;而對於 CSS 和圖片也一樣可以。
IE,你可以用熟悉的 image beacon 模式送出一個請求:
在其他瀏覽器,你可以用
<object>
替代 script 元素,並設定其
data
屬性指向 script 所在
URL
為避免此 object 標籤被看見,你也應該設定其
width
height
屬性為 0
你可以建立一個泛用的
preload()
函式或方法,用初始階段的分枝模式(第四章)來處理
瀏覽器間的差異:
[205]
用條件註解(conditional comments)來進行 IE 的偵測
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

JavaScript 之美

JavaScript 之美

Anton Kovalyov
重構 JavaScript

重構 JavaScript

Evan Burchard

Publisher Resources

ISBN: 9789862764190