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 設計模式
DOM 和瀏覽器的模式
   
209
[200]
這種實踐方式非常符合漸進式增強和 unobtrusive JavaScript 的精神。在第二個 HTML 分塊
完成之後,你應該就有個已經完整載入、顯示,且可用的頁面,就跟 JavaScript 在瀏覽器
中被停用的情況是一樣的。而在 JavaScript 隨著第三個分塊抵達後,它就強化了頁面、加
入了產品的特色和性能。
用動態 <script> 實現非同步下載
如前面所提過的,JavaScript 會阻擋在它之後的檔案下載。不過有幾個模式讓你可以避免:

XHR 請求來下載 script,並用
eval()
執行下載的字串。這種做法受到來自同一網
域的限制,還必須用到
eval()
,而這東西本身就是個反模式。

使用
defer
async
屬性,但這些並非在所有瀏覽器都有效。

使用動態的
<script>
元素。
最後一種模式優良又可行,它類似你在 JSONP 看到的做法,你建立一個新的
script
素,設定其
src
,接著附加到頁面上。
底下是一個範例,用來載入一個 JavaScript 檔案,且不會阻擋其他的下載:
<!--
1
段分塊結束
-->
<!--
2
段分塊結束
-->
<!--
3
段分塊結束
-->
210
   
第八章
此模式的缺點是,如果主要的 .js 檔案正用此模式下載,你就不能下載任何其他需倚賴此
主要 script 的檔案。因為主要的 .js 檔是用非同步下載,所以無法保證何時會完 ...
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