| [Web] 被遺忘的知識(shí)點(diǎn) - JavaScript加載管理最佳實(shí)踐前言 
 最近項(xiàng)目有一個(gè)需求,如下: HTML頁(yè)面一般來(lái)說(shuō)可以由CSS、JavaScript、Dom(通常為Div)以及一些JS初始化頁(yè)面函數(shù)組成,現(xiàn)在需要將一個(gè)頁(yè)面拆分為CSS、 JavaScript、Dom和JS init函數(shù)四部分,通過(guò)從服務(wù)端分別獲取這四部分,經(jīng)過(guò)拼湊后,渲染出完整的頁(yè)面。這里面CSS、DOM節(jié)點(diǎn)比較好處理,但是JavaScript的加 載以及JS init的執(zhí)行,就要考慮到很多問(wèn)題。如果有誰(shuí)遇到類似的問(wèn)題,可以討論下,畢竟想要將這個(gè)做成一個(gè)完善的框架會(huì)遇到很多問(wèn)題。這篇文章,我將介紹一些加 載管理JavaScript的一些實(shí)踐,希望對(duì)你有所幫助。 原生的JavaScript實(shí)現(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實(shí)現(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實(shí)現(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(); }); | 
|  | 
來(lái)自: quasiceo > 《計(jì)算機(jī)》