简体   繁体   English

延迟加载JavaScript,Jquery'ready()'在加载JQuery之前运行

[英]Defer loading in JavaScript, Jquery 'ready()' runs before JQuery is loaded

I am loading two JS files, one with many plugins, including Jquery. 我正在加载两个JS文件,一个包含许多插件,包括Jquery。 The 'ready()' JQuery function is in the second file. 'ready()'JQuery函数位于第二个文件中。

Code: 码:

   function downloadJSAtOnload() {

       var element = document.createElement("script");
       element.src ='<%= deferJsAll %>';
       document.body.appendChild(element);

      // second JS file load with isReady goes here
   }

   // Check for browser support of event handling capability
   if (window.addEventListener)
       window.addEventListener("load", downloadJSAtOnload, false);
   else if (window.attachEvent)
       window.attachEvent("onload", downloadJSAtOnload);
   else window.onload = downloadJSAtOnload;

You can see when I also load the second file (See comment inside the code). 您可以看到我何时加载第二个文件(请参阅代码中的注释)。

The problem is that I can't control the order of execution and even so, the 'ready()' runs before JQuery is loaded, and I get an error. 问题是我无法控制执行的顺序,即便这样,'ready()'在加载JQuery之前运行,我得到一个错误。 Is there an option to use defer loading and making sure that the Jquery files loads first and then the second is executed (the one with the ready() function)? 是否有选项可以使用延迟加载并确保首先加载Jquery文件然后执行第二个(带有ready()函数的文件)?

I am using "<%= deferJsAll %>" because I am deciding which file to serve from CDN, the gzip or plain text JS file. 我正在使用“<%= deferJsAll%>”因为我决定从CDN,gzip或纯文本JS文件提供哪个文件。

Progress: I thought about just putting: 进展:我想过刚才:

var elementApp = document.createElement("script");
elementApp.src = 'js/app.js';
document.body.appendChild(elementApp);

at the end of the first document. 在第一份文件的最后。 So when the first document finishes loading, it will then embed the second dependent JS code into the body of the document. 因此,当第一个文档完成加载时,它会将第二个相关的JS代码嵌入到文档的主体中。 Do you think it's a good idea? 你认为这是个好主意吗?

You can use onload & onreadystatechange (for IE) to detect when the script is finished loading. 您可以使用onload&onreadystatechange(对于IE)来检测脚本何时完成加载。

function loadScript(callback){
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = '<%= deferJsAll %>';
  document.body.appendChild(script);

  // exit on jQuery load.
  script.onload = function(){ callback(); };
  script.onreadystatechange = function() {
    if (this.readyState == 'complete') callback();
  }
}


loadScript(function(){
  $.getScript('<% jquery-dependent.js %>', function(){
     // jquery-dependent.js is loaded
  }
});

Here's a solution I used when I need to wait until some var on the page exists. 这是我在需要等到页面上的某些var存在时使用的解决方案。 It takes a name (eg jQuery or namespace twttr.widgets with arbitrary depth) and other self explanatory attributes. 它需要一个名称(例如具有任意深度的jQuery或名称空间twttr.widgets )和其他自解释属性。 Works in production on http://www.vitalmtb.com/ when I need to wait till Facebook and Twitter widgets are loaded. 当我需要等到Facebook和Twitter小部件被加载时,才能在http://www.vitalmtb.com/上投入生产。

// Wait till JS object is loaded. It can be a chanined variable name.
window.whenAvailable = function (name, callback, interval, max_wait) {
    interval || (interval = 50); // ms
    max_wait || (max_wait = 5000); // ms
    var timer,
        findVarByName = function(name) {
        var index = 0,
            parts = name.split('.'),
            result = window;

        index = 0;
        try {
            while (typeof result !== "undefined" && result !== null && index < parts.length) {
                result = result[parts[index++]];
            }
        }
        catch (e) {}
        if (index < parts.length || (typeof result == 'undefined' && result === undefined)) return false;
        else return true;
    };

    timer = window.setTimeout(function() {
        if (findVarByName(name)) {
            return callback();
        } else {
            window.setTimeout(arguments.callee, interval);
        }
    }, interval);

    window.setTimeout(function() {
        clearTimeout(timer);
    }, max_wait);
}

Use: 采用:

whenAvailable('FB', $j.spotlights.a.show_social_buttons);
whenAvailable('twttr.widgets', $j.spotlights.b.show_social_buttons);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM