zoukankan      html  css  js  c++  java
  • 判断脚本加载完成

    在“按需加载”的需求中,我们经常会判断当脚本加载完成时,返回一个回调函数,那如何去判断脚本的加载完成呢?

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

    对于 readyState 状态需要一个补充说明:

    1. 在 interactive 状态下,用户可以参与互动。
    2. Opera 其实也支持 js.onreadystatechange,但他的状态和 IE 的有很大差别。
     1 function include_js(file) {
     2     var _doc = document.getElementsByTagName('head')[0];
     3     var js = document.createElement('script');
     4     js.setAttribute('type', 'text/javascript');
     5     js.setAttribute('src', file);
     6     _doc.appendChild(js);
     7 
     8     if (!/*@cc_on!@*/0) { //if not IE
     9         //Firefox2、Firefox3、Safari3.1+、Opera9.6+ support js.onload
    10         js.onload = function () {
    11             alert('Firefox2、Firefox3、Safari3.1+、Opera9.6+ support js.onload');
    12         }
    13     } else {
    14         //IE6、IE7 support js.onreadystatechange
    15         js.onreadystatechange = function () {
    16             if (js.readyState == 'loaded' || js.readyState == 'complete') {
    17                 alert('IE6、IE7 support js.onreadystatechange');
    18             }
    19         }
    20     }
    21 
    22     return false;
    23 }
    24 
    25 //execution function
    26 include_js('http://www.planabc.net/wp-includes/js/jquery/jquery.js');
    一个不敬业的前端攻城狮
  • 相关阅读:
    449. Serialize and Deserialize BST
    3. Longest Substring Without Repeating Characters
    2. Add Two Numbers
    240. Search a 2D Matrix II
    5. Longest Palindromic Substring
    数位DP专题(开坑。
    POJ 2356
    HDU 4055
    HDU 4054
    HDU 1559
  • 原文地址:https://www.cnblogs.com/chaoming/p/3361709.html
Copyright © 2011-2022 走看看