1.推薦所有的script標簽盡可能放到body標簽的底部,以盡量減少對整體頁面下載速度的影響。
2.組織腳本
減少頁面包含的scirpt標簽數量,可以把多個文件合并成一個。
3.無阻塞腳本
1).延遲腳本
defer:html解析完才加載,執行順序和加載順序有關。
async:html加載完就執行,執行順序和加載順序無關。
2).動態腳本元素(推薦)
文件在該元素被添加到頁面時開始下載。這種技術的中i單在于:無論在何時啟動下載,文件的下載和執行過程呢個不會阻塞頁面其他進程。
但是有兼容問題,解決辦法如下:
function loadScript(url, callback) {var script = document.createElement_x_x('script');script.type = "text/javascript";if (script.readyState) {//IEscript.onreadystatechange = function () {if (script.readyState == 'loaded' || script.readyState == 'complete') {script.onreadystatechange = null;callback();}};}else{//其他瀏覽器script.onload=function(){callback();}};script.scr=url;document.getElementsByTagName('head')[0].a(script);};loadScript('file.js',function(){console.log('file.js is loaded')});
loadScript('file.js',function(){loadScript('file2.js',function(){loadScript('file3.js',function(){console.log('all is load')})})});復制代碼
XMLHttpRequest腳本注入(大型web不推薦)
var xhr=new XMLHttpRequest();xhr.open('get','file.js',true);xhr.onreadystatechange=function(){if(xhr.readyState==4){if(xhr.status>=200&&xhr.status<<span style="color: #b5cea8;">300||xhr.status==304){var script=document.createElement_x_x('script');script.type='text/javascript';script.text='xhr.responseText';document.body.a(script)}}};xhr.send(null);復制代碼
總結:減少JavaScript對性能的影響。
1./body閉合標簽之前,將所有的script標簽放在頁面底部。這樣確保在腳本執行前頁面已經完成了渲染。
2.合并腳本,頁面中的script標簽也少,加載也就越快,響應也就越快,無論外鏈還是內嵌腳本都是如此。
3.使用多種無阻塞的javascript方法:
3.1使用script的方法defer屬性。
3.2使用動態創建script元素來下載并執行代碼。
3.3使用XHR對象下載javascript代碼并注入頁面中