How to know if JQuery has finished loading

This question already has an answer here:

  • How do I include a JavaScript file in another JavaScript file? 50 answers

  • You will have to write code to detect when a dynamically loaded script is loaded and unfortunately, it works slightly different in some older browsers so it isn't as simple as it could be. Here's a good reference article on how to do that: http://www.ejeliot.com/blog/109

    Here's some of the code from that article:

    function loadScript(sScriptSrc, oCallback) {
    
        var oHead = document.getElementsByTagName('head')[0];
        var oScript = document.createElement('script');
    
        // make sure callback isn't run more than once
        function runCallback() {
            if (oCallback) {
                oCallback();
                oScript.onload = oScript.onreadystatechange = null;
                oCallback = null;
            }
        }
    
        oScript.type = 'text/javascript';
        // most browsers
        oScript.onload = runCallback;
        // IE 6 & 7
        oScript.onreadystatechange = function() {
            if (this.readyState === 'complete') {
                runCallback();
            }
        }
        oScript.src = sScriptSrc;
        oHead.appendChild(oScript);
    }
    

    Alternatively, you could use one of the tiny libraries that does this work for you. You can see a list of some of those here: http://microjs.com/#loader. Though I'm not sure you want to use yet another library to assist with loading your primary library.


    尝试onload事件:

     //.....
     script.onload = function(){
         alert('jQuery is loaded succesfully').
     };
     script.src = "https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js";
    

    Kudos for jfriend's answer. Callbacks are sexy.

    Second crack at it.

    function loadJQ(callback) {
      if(!window.jQuery) {
        // Create jQuery script element.
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = 'path/to/jquery.js';
        document.body.appendChild(script);
    
        script.onload = function(){ callback(jQuery); };
        // IE 6 & 7 ala jfriend00
        script.onreadystatechange = function() {
          if (this.readyState == 'complete') callback(jQuery);
        }
      } else {
        callback(jQuery);
      }
    }
    

    Invocation

    loadJQ(function($){
      alert($ === jQuery); // true. jquery is loaded.
    });
    
    链接地址: http://www.djcxy.com/p/7346.html

    上一篇: 等同于Python导入的JavaScript?

    下一篇: 如何知道JQuery是否完成加载