高效能JavaScript_編程—筆記一(Loading and Execution載入和運行)

來源:互聯網
上載者:User

1.javascript載入

順序:盡量在頁面底部載入js檔案

數量:盡量將若干javascript代碼塊打包成一個js檔案引入(打包工具[yahoo!combo hander])

js屬性defer:若某塊js代碼添加有defer屬性,則在dom元素載入之前不會執行(不管該js代碼塊放在哪裡,注意:某些瀏覽器不支援該屬性)

                         例子:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312" /><title>無標題文檔</title></head><script defer="defer">alert("defer");</script><body><script>alert("script")</script><script>window.onload=function(){alert("load");}</script></body></html>

彈出順序為script,defer,load,若沒有defer屬性或瀏覽器不支援,則順序為defer,script,load

動態指令碼元素: dynamic script elements

使用動態載入節點下載時候,返回的代碼會立即執行(FF,opera除外,他們將等待此前的指令碼執行完畢),這樣當指令碼是“自運行”類型(即和其他js指令碼無關聯,獨立性很強的)的這一機制則運行正常,但是如果包含供頁面其他指令碼調用的介面,則會帶來問題,這時就必須等待該檔案完全載入完畢,FF,opera,chrome,safari3+在<script>節點接收完全之後發出一個Load事件.我們可以監聽這一事件來判斷js指令碼是否載入完畢,代碼如:

            

IE支援另外一種實現方式,他發出一個onreadystatechange事件,<script>有一個readyState屬性,它的值伴隨著被下載檔案的狀態而改變

    

a>通過下面的函數可以實現載入頁面javascript檔案並提供入口函數:

<script type="text/javascript"> function loadScript(url,callback){var script = document.createElement("script");script.type="text/javascript";if(script.readyState){//IEscript.onreadystatechange = function(){if(script.readyState=="loaded"||script.readyState=="complete"){script.onreadystatechange=null;    callback();}}}else{//othersscript.onload = function(){        callback();}}script.src = url;document.getElementsByTagName("head")[0].appendChild(script);}loadScript("test.js",function(){ console.log("callback() success")})</script>
test.js檔案 : console.log("the test.js  load success");

b>LazyLoad是一個更強大的類似loadScript函數,精縮只有1.5KB     

LazyLoad.js("test.js",function(){     console.log("test.js loaded success");})

  

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.