小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

被遺忘的知識(shí)點(diǎn) - JavaScript加載管理最佳實(shí)踐

 quasiceo 2013-03-07

[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)


 此處為不希望借助框架的朋友們,提供一種方案。

復(fù)制代碼
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);
}
復(fù)制代碼

LAB實(shí)現(xiàn)


 

復(fù)制代碼
$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();
});
復(fù)制代碼
復(fù)制代碼
$LAB.setOptions({
  AllowDuplicates: true
})
.script("script1.js").wait()
.script("script2.js")
.script("script3.js").wait()
.script("script4.js")
.wait(function () {
  initFunction();
});
復(fù)制代碼

RequireJS實(shí)現(xiàn)


 

復(fù)制代碼
(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();
});
復(fù)制代碼

    本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購(gòu)買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊一鍵舉報(bào)。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評(píng)論

    發(fā)表

    請(qǐng)遵守用戶 評(píng)論公約

    類似文章 更多