當前位置:編程學習大全網 - 源碼下載 - 動態加載JS過程中如何判斷JS加載完成

動態加載JS過程中如何判斷JS加載完成

在正常的加載過程中,js文件的加載是同步的,也就是說在js加載的過程中,瀏覽器會阻塞接下來的內容的解析。這時候,動態加載便顯得尤為重要了,由於它是異步加載,因此,它可以在後臺自動下載,並不會妨礙其它內容的正常解析,由此,便可以提高頁面首次加載的速度。

在IE或壹些基於IE內核的瀏覽器中(如Maxthon),它是通過script節點的readystatechange方法來判斷的,而其它的壹些瀏覽器中,往往是通過load事件來決定的,如下代碼:

function dynamicLoad(){var _doc=document.getElementsByTagName('head')[0];

var script=document.createElement('script');

script.setAttribute('type','text/javascript');

script.setAttribute('src','jquery-1.4.4.js');

script.onload=script.onreadystatechange=function(){

if(!this.readyState||this.readyState=='loaded'||this.readyState=='complete'){

alert('done');}script.onload=script.onreadystatechange=null;}}

這是因為,如果script節點沒有添加到DOM樹中,那麽在chrome和firefox中是不會響應script的load事件的。但是IE中卻可以。。修改後如下代碼:

function dynamicLoad(){var _doc=document.getElementsByTagName('head')[0];

var script=document.createElement('script');

script.setAttribute('type','text/javascript');

script.setAttribute('src','jquery-1.4.4.js');

_doc.appendChild(script);

script.onload=script.onreadystatechange=function(){

if(!this.readyState||this.readyState=='loaded'||this.readyState=='complete'){

這時候,所有的瀏覽器都可以響應,妳可以嘗試壹下~

  • 上一篇:制作html的類似eclips的工具
  • 下一篇:怎樣學好前端從入門開始
  • copyright 2024編程學習大全網