來源:GBin1.com

RequireJS 掀起非同步載入與 AMD 格式巨大浪潮。XMLHttpRequest(AJAX 核心)使資源非同步載入普及,允許無阻塞載入、加速 onload 觸發、無需重新整理即可載入內容。
筆者使用 John Hann 的 curl 載入器:基礎非同步載入器、可配置、擁有優秀插件生態。以下 curl 代碼片段:
// 基本用法:載入 AMD 模組
curl(['social', 'dom'], function(social, dom) {
dom.setElementContent('.social-container', social.loadWidgets());
});
// 定義使用 Google Analytics 的非 AMD 模組
define(["js!//google-analytics.com/ga.js"], function() {
return {
trackPageView: function(href) {
_gaq.push(["_trackPageview", url]);
},
trackEvent: function(eventName, href) {
_gaq.push(["_trackEvent", "Interactions", eventName, "", href || window.location, true]);
}
};
});
// 載入無回調的非 AMD JS 檔案
curl(['js!//somesite.com/widgets.js']);
// 將 JS 與 CSS 作為模組載入
curl(['js!libs/prism/prism.js', 'css!libs/prism/prism.css'], function() {
Prism.highlightAll();
});
// 載入 AJAX 請求的 URL
curl(['text!sidebar.php', 'storage', 'dom'], function(content, storage, dom) {
storage.set('sidebar', content, 60);
dom.setElementContent('.sidebar', content);
});
非同步載入能大幅提升萬維網展示速度,關鍵在於你要去用它!用了就能看到差別,更重要的是使用者能感受到差別。
當你能根據頁面內容延遲載入依賴時,才能真正體會優勢。例:只在套用名為 social 的 CSS 樣式的 div 中載入 Twitter、Facebook、Google Plus。「載入前檢查是否需要」策略能為使用者省下好幾 KB 無謂載入。
下一篇將介紹用 Array.prototype.join 取代字串連接,提升前端效能。
via Nelly @ 極客社區 | 來源:https://www.gbin1.com/technology/javascript/20130701-front-end-performance-optimization-4/