web页面优化之动态加载js和文件
生活随笔
收集整理的這篇文章主要介紹了
web页面优化之动态加载js和文件
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
關于按需加載js,從而提高頁面加載性能:
以京東商品詳情頁面為例:
首次打開時,會加載一部分js,當下拉滾動條時,會促發事件,從而以jsponp形式異步加載一些js文件,如評論調用的js文件:
http://club.360buy.com/clubservice/newproductcomment-681391-3-0.html?callback=fetchJSON_CommentList(這個鏈接會被調用,從而加載對應的json數據,再配合實現先好的jsonp處理函數去處理,把結果賦值到對應的位置:
如下是fetchJSON_CommentList實現寫好的回調函數
$(".btn-comment").livequery("click", function() {var a = $(this).attr("href");$.extend(jdModelCallCenter.settings, {clstag1: 0,clstag2: 0,fn: function() {jdModelCallCenter.autoLocation(a)}});jdModelCallCenter.settings.fn();return false }); var CommentList = {getData: function(b, c, d) {var f = this,b = b || 0,c = c || 0,d = d,a = "http://club.360buy.com/clubservice/newproductcomment-" + G.sku + "-" + b + "-" + c + ".html";if (b == 1) {b = 3} else {if (b == 3) {b = 1}}window.fetchJSON_CommentList = function(g) {if (!$("#comment .mc").hasClass("loaded")) {if (parseInt(g.CommentSummary.CommentCount) !== 0) {$("#comment").show();$("#comment .mc").addClass("loaded").html(commentRate_TPL.process(g))} else {$("#comment").attr("nodata", "true").hide()}$("#comments-list .tab li").each(function() {var j = $("#comments-list .tab li").index($(this)),h = $(this).find("em");switch (j) {case 0:h.html("(" + g.CommentSummary.CommentCount + ")");break;case 1:h.html("(" + g.CommentSummary.GoodCount + ")");break;case 2:h.html("(" + g.CommentSummary.GeneralCount + ")");break;case 3:h.html("(" + g.CommentSummary.PoorCount + ")");break;case 4:h.html("(" + g.CommentSummary.ShowCount + ")");break}})}f.setItem(d, g, b, c)};$.getJSONP("http://club.360buy.com/clubservice/newproductcomment-" + G.sku + "-" + b + "-" + c + ".html?callback=fetchJSON_CommentList")},setItem: function(f, d, a, c) {var j = this,b = f,a = a || 0,c = c || 0,h = f.attr("id"),g = "";f.html(commentList_TPL.process(d));switch (h) {case "comment-0":g = "CommentCount";break;case "comment-1":g = "GoodCount";break;case "comment-2":g = "GeneralCount";break;case "comment-3":g = "PoorCount";break;case "comment-4":g = "ShowCount";break;default:g = "CommentCount"}$("#commentsPage" + d.Score).pagination(d.CommentSummary[g], {items_per_page: 7,num_display_entries: 5,current_page: c,num_edge_entries: 2,link_to: "#comments-list",prev_text: "\u4e0a\u4e00\u9875",next_text: "\u4e0b\u4e00\u9875",ellipse_text: "...",prev_show_always: false,next_show_always: false,callback: function(k, l) {if (a == 1) {a = 3} else {if (a == 3) {a = 1}}j.getData(a, k, b)}})} };?
?以下參考:
http://www.aichengxu.com/article/Javascript/610_7.html
s無非就是script標簽引入頁面,但當項目越來越大的時候,單頁面引入N個js顯然不行,合并為單個文件減少了請求數,但請求的文件體積卻很大。 這時候最好的做法就是按需引入,動態引入組件js和樣式,文件load完成后調用callback,運行js。代碼還是很簡便的 1. 判斷文件load完成。加載狀態ie為onreadystatechange,其他為onload、onerrorif(isie){ Res.onreadystatechange = function(){ if(Res.readyState == 'complete' || Res.readyState == 'loaded'){ Res.onreadystatechange = null; callback(); _self.loadedUi[modelName] = true; } } }else{ Res.onload = function(){ Res.onload = null; callback(); _self.loadedUi[modelName] = true; } Res.onerror = function(){ throw new Error('res error:' + modelName+'.js'); } } 2. 所有組件的命名最好保持一致,callback調用也比較方便。還可以根據需要增加參數比如: requires,依賴于那些文件;style,true || false,是否加載樣式,等等。 3. 移除操作也可以有,移除script、style標簽、delete組件(function(window,undefined){ if(!window.ui) { window.ui = {}; } //動態加載ui的js window.bus = { config : { version : window.config.version, cssPath : window.config.resServer + '/css/v3/ui', jsPath : window.config.resServer + '/js/v2/ui' }, loadedUi : {}, readyStateChange : function(){ var ua = navigator.userAgent.toLowerCase(); return ua.indexOf('msie') >= 0; }, loadRes : function(modelName,prames,callback){ var _self = this; var Res = document.createElement(prames.tagName); for(var k in prames){ if(k != 'tagName'){ Res.setAttribute(k,prames[k],0); } } document.getElementsByTagName('head')[0].appendChild(Res); if(this.readyStateChange()){ Res.onreadystatechange = function(){ if(Res.readyState == 'complete' || Res.readyState == 'loaded'){ Res.onreadystatechange = null; callback(); _self.loadedUi[modelName] = true; } } }else{ Res.onload = function(){ Res.onload = null; callback(); _self.loadedUi[modelName] = true; } Res.onerror = function(){ throw new Error('res error:' + modelName+'.js'); } } }, removeUi : function(modelName){ if(!modelName){ return true }; this.loadedUi[modelName] = false; var head = document.getElementsByTagName('head')[0]; var model_js = document.getElementById('J_model_'+modelName + '_js'); var model_css = document.getElementById('J_model_'+modelName + '_css'); if(model_js && model_css){ delete window.ui[modelName]; head.removeChild(model_js); head.removeChild(model_css); return true; }else{ return false; } }, loadUi : function(modelName,callback,setting){ if(!modelName){ return true }; callback = callback || function(){}; if(this.loadedUi[modelName] == true){ callback(); return true } var deafult_setting = { style : true, js : true, requires : [] } for(var key in setting){ deafult_setting[key] = setting[key]; } deafult_setting['style'] === true && this.loadRes(modelName,{ id : 'J_model_'+modelName + '_css', name : modelName, tagName : 'link', type : 'text/css', rel : 'stylesheet', href : this.config.cssPath + '/' + modelName + '.css?v=' + this.config.version }); deafult_setting['js'] === true && this.loadRes(modelName,{ id : 'J_model_'+modelName + '_js', name : modelName, tagName : 'script', type : 'text/javascript', src : this.config.jsPath + '/' + modelName + '.js?v=' + this.config.version },callback); if(deafult_setting.requires.length > 0){ for(var i=0,len = deafult_setting.requires.length;i<len;i++){ this.loadUi(deafult_setting.requires[i]); } } } } })(window)使用方法// load comment for feed window.bus.loadUi('new_comment_feed', function(){ window.ui.new_comment_feed($("#J_newsList")); },{ style : false, requires:['emoticon','addFriend'] }); // load new yy ui window.bus.loadUi('yy', function(){ window.ui.yy(options); },{ style:false, requires:['emoticon'] }); // load photoLightbox window.bus.loadUi('photoLightbox', function(){ window.ui.photoLightbox(options.urlAjaxGetFriendPhoto, options.urlCommentOtherPhoto,$("#J_newsList"),options.myUid,options.myName); });?
轉載于:https://www.cnblogs.com/Alight/archive/2013/02/03/2890903.html
總結
以上是生活随笔為你收集整理的web页面优化之动态加载js和文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 工作总结2013
- 下一篇: Linux软件安装之RPM的安装技巧