zoukankan      html  css  js  c++  java
  • 同步按顺序动态加载JS

    我们知道, 现代主流浏览器(如chrome)加载js是异步执行的,会同时加载多个js,那么当我们需要在js中动态加载其他的js时候,他们的完成顺序并不是像我们主观想象的那样,先写的先加载。例如:

    1. function loadScript(url, fn) {
    2. var script = document.createElement("script");
    3. script.type = "text/javascript";
    4. script.src = url;
    5. script.onload = script.onreadystatechange = function () {
    6. if (!script.readyState || 'loaded' === script.readyState || 'complete' === script.readyState) {
    7. fn && fn();
    8. }
    9. };
    10. script.src = url;
    11. document.head.appendChild(script);
    12. }
     

     这是一段动态加载js的代码,倘若写成:

    1. loadScript("http://cdn.bootcss.com/Chart.js/2.0.0-alpha3/Chart.js",function(){document.getElementById("test").innerHTML+="chart;"});
    2. loadScript("http://cdn.bootcss.com/jquery/1.11.2/jquery.js",function(){document.getElementById("test").innerHTML+="jquery;"; });
    3. loadScript("http://cdn.gbtags.com/jquery-color/2.1.2/jquery.color.min.js",function(){document.getElementById("test").innerHTML+="jq-color;"});
    4. loadScript("http://cdn.gbtags.com/jquery-easing/1.3/jquery.easing.min.js",function(){document.getElementById("test").innerHTML+="jq-easing;"});
     
     

      那么结果正常情况下是:

    1. chart;jquery;jq-color;jq-easing;

     你以为所有情况都是这种理想情况吗?too young ! too simple ! 假如加载速度都非常快的时候,或者js都存在缓存时候也许会这样!大多数情况下是这样的:

    1. jquery;jq-color;jq-easing;chart;
    2. 或者
    3. jq-color;jq-easing;jquery;chart;
    1. 等等

    可见顺序不是固定的,假如写在后面的easing.js又用到了前面jquery.js的内容,哇!肯定就会出现一系列的undefined错误,想想就可怕!

    那么!我们就必须在动态加载js的时候将异步变为同步

    如下所示:newScripts是一个将要加载的script的顺序集合,采用迭代方法将他们依次加载,确保加载执行顺序: 

    1. var newScripts = ["http://cdn.bootcss.com/Chart.js/2.0.0-alpha3/Chart.js",
    2. "http://cdn.bootcss.com/jquery/1.11.2/jquery.js",
    3. "http://cdn.gbtags.com/jquery-color/2.1.2/jquery.color.min.js",
    4. "http://cdn.gbtags.com/jquery-easing/1.3/jquery.easing.min.js"];
    5. //迭代加载,callback为全部加载完成后的回调函数
    6. (function scriptRecurse(count, callback) {
    7. if (count == newScripts.length) {
    8. callback && callback();
    9. } else {
    10. loadScript(newScripts[count], function () {
    11. document.getElementById("test2").innerHTML+=newScripts[count]+";<br>";
    12. scriptRecurse(++count, callback);
    13. });
    14. }
    15. })(0);

    原文链接:http://www.gbtags.com/gb/share/5947.htm

  • 相关阅读:
    全面整理的C++面试题
    在chrome下安装Proxy SwitchySharp插件
    VC中获取窗体句柄的各种方法
    炙手可热的12款站点模板推荐
    _blank开新窗体不符合标准?
    欢迎大家来我的小站
    白话经典算法系列之中的一个 冒泡排序的三种实现
    CRF++使用小结(转)
    智能点餐系统开发纪实2-----系统总体结构和业务流程
    Windows Mobile 6.0 SDK和中文模拟器下载
  • 原文地址:https://www.cnblogs.com/gbtags/p/4702164.html
Copyright © 2011-2022 走看看