[Web] 被遺忘的知識點 - JavaScript加載管理最佳實踐前言
最近項目有一個需求,如下: HTML頁面一般來說可以由CSS、JavaScript、Dom(通常為Div)以及一些JS初始化頁面函數(shù)組成,現(xiàn)在需要將一個頁面拆分為CSS、 JavaScript、Dom和JS init函數(shù)四部分,通過從服務端分別獲取這四部分,經(jīng)過拼湊后,渲染出完整的頁面。這里面CSS、DOM節(jié)點比較好處理,但是JavaScript的加 載以及JS init的執(zhí)行,就要考慮到很多問題。如果有誰遇到類似的問題,可以討論下,畢竟想要將這個做成一個完善的框架會遇到很多問題。這篇文章,我將介紹一些加 載管理JavaScript的一些實踐,希望對你有所幫助。 原生的JavaScript實現(xiàn) 此處為不希望借助框架的朋友們,提供一種方案。 function loadScript(url, callback) { var script = document.createElement("script") script.type = "text/javascript"; if (script.readyState) { //IE script.onreadystatechange = function () { if (script.readyState == "loaded" || script.readyState == "complete") { script.onreadystatechange = null; callback(); } }; } else { //Others script.onload = function () { callback(); }; } script.src = url; document.getElementsByTagName("head")[0].appendChild(script); } LAB實現(xiàn)
$LAB.setOptions({ AlwaysPreserveOrder: true }) .script("script1.js") // script1, script2, script3, and script4 *DO* depend on each .script("script2.js") // other, and will execute serially in order after all 4 have have .script("script3.js") // loaded in parallel .script("script4.js") .wait(function () { initFunction(); }); $LAB.setOptions({ AllowDuplicates: true }) .script("script1.js").wait() .script("script2.js") .script("script3.js").wait() .script("script4.js") .wait(function () { initFunction(); }); RequireJS實現(xiàn)
(function (require) { var urlArgs = ''; // used for browser cache if (CNBlogs.isProduct) { urlArgs = 'v=1'; } else { urlArgs = "dev=" + (new Date()).getTime(); } require.config({ baseUrl: '/scripts', //By default load any module IDs from baseUrl urlArgs: urlArgs, paths: { 'hello1': 'hello1.min', 'hello2': '/document/11111-11100-010101/latest?' // append ? to avoid .js extension }, shim: { 'hello3': ['hello1', 'hello2'], 'hello4': ['hello3', 'bootstrap'] }, waitSeconds: 200 }); })(require); require(['jqueryui', 'hello4'], function () { initFunction(); }); |
|
|