動態載入js提高網頁開啟速度的方法_javascript技巧

來源:互聯網
上載者:User

一般來說如果一次性的載入所有需要的JavaScript代碼,就會造成初始頁面開啟速度變慢,但是很多載入的代碼又並不需要使用,這種無謂的效能浪費應該予以避免。如果要動態載入JavaScript代碼,可以利用DOM模型在HTML文檔中添加<script>結點,並將此結點的src屬性(即 外聯 Javascript檔案)設定為需要動態載入的JavaScript代碼。

下面就是完成這樣功能的一個樣本:

(1)、建立JsLoaderTest.html檔案

<html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>按需載入JavaScript代碼的例子</title> <script type="text/javascript">   function JsLoader(){   this.load=function(url){       //擷取所有的<script>標記       var ss=document.getElementsByTagName("script");       //判斷指定的檔案是否已經包含,如果已包含則觸發onsuccess事件並返回       for (i=0;i<ss.length;i++){         if (ss[i].src && ss[i].src.indexOf(url)!=-1){           this.onsuccess();           return;         }       }       //建立script結點,並將其屬性設為外聯JavaScript檔案       s=document.createElement("script");       s.type="text/javascript";       s.src=url;       //擷取head結點,並將<script>插入到其中       var head=document.getElementsByTagName("head")[0];       head.appendChild(s);       //擷取自身的引用       var self=this;       //對於IE瀏覽器,使用readystatechange事件判斷是否載入成功       //對於其他瀏覽器,使用onload事件判斷載入是否成功       //s.onload=s.onreadystatechange=function(){       s.onload=s.onreadystatechange=function(){         //在此函數中this指標指的是s結點對象,而不是JsLoader執行個體,         //所以必須用self來調用onsuccess事件,下同。         if (this.readyState && this.readyState=="loading") return;         self.onsuccess();       }       s.onerror=function(){         head.removeChild(s);         self.onfailure();       }     };     //定義載入成功事件     this.onsuccess=function(){};     //定義失敗事件     this.onfailure=function(){};   }   function btnClick(){       //建立對象     var jsLoader=new JsLoader();     //定義載入成功處理常式     jsLoader.onsuccess=function(){        sayHello();     }     //定義載入失敗處理常式     jsLoader.onfailure=function(){        alert("檔案載入失敗!");     }     //開始載入     jsLoader.load("hello.js");   } </script> </head> <body> <label> <input type="submit" name="Submit" onClick="javascript:btnClick()" value="載入JavaScript檔案"> </label> </body> </html> 

(2)、建立hello.js檔案,包含如下代碼:

// JavaScript Document function sayHello(){   alert("Hello World!成功載入JavaScript檔案");   } // JavaScript Documentfunction sayHello(){  alert("Hello World!成功載入JavaScript檔案");  }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.