JS判断脚本是否加载完成

canca canca
2008-12-01 19:15
2
0
  1. 在“按需加载”的需求中,我们经常会判断当脚本加载完成时,返回一个回调函数,那如何去判断脚本的加载完成呢?

    我们可以对加载的 JS 对象使用 onload 来判断(js.onload),此方法 Firefox2、Firefox3、Safari3.1+、Opera9.6+ 浏览器都能很好的支持,但 IE6、IE7 却不支持。曲线救国 —— IE6、IE7 我们可以使用 js.onreadystatechange 来跟踪每个状态变化的情况(一般为 loading 、loaded、interactive、complete),当返回状态为 loaded 或 complete 时,则表示加载完成,返回回调函数。

    对于 readyState 状态需要一个补充说明:
    在 interactive 状态下,用户可以参与互动。
    Opera 其实也支持 js.onreadystatechange,但他的状态和 IE 的有很大差别。

    具体实现代码如下:

  2. function include_js(file) {   
  3.     var _doc = document.getElementsByTagName('head')[0];   
  4.     var js = document.createElement('script');   
  5.     js.setAttribute('type''text/javascript');   
  6.     js.setAttribute('src', file);   
  7.     _doc.appendChild(js);   
  8.   
  9.     if (!/*@cc_on!@*/0) { //if not IE   
  10.         //Firefox2、Firefox3、Safari3.1+、Opera9.6+ support js.onload   
  11.         js.onload = function () {   
  12.             alert('Firefox2、Firefox3、Safari3.1+、Opera9.6+ support js.onload');   
  13.         }   
  14.     } else {   
  15.         //IE6、IE7 support js.onreadystatechange   
  16.         js.onreadystatechange = function () {   
  17.             if (js.readyState == 'loaded' || js.readyState == 'complete') {   
  18.                 alert('IE6、IE7 support js.onreadystatechange');   
  19.             }   
  20.         }   
  21.     }   
  22.   
  23.     return false;   
  24. }   
  25.   
  26. //execution function   
  27. include_js('http://www.planabc.net/wp-includes/js/jquery/jquery.js');  


转自:http://www.52web.com/52article/?view-235.html

发表评论