动态加载jQuery并使用它

时间:2015-01-28 04:55:17

标签: javascript jquery

如果尚未加载jQuery库,如何正确加载?

somepage.html:

<script src="http://example.com/js/widget_init.js" type="text/javascript"></script>

<script type="text/javascript">
  if (typeof jQuery == 'undefined') {  
    console.log('ERROR: NOT LOADED');
  }
  else{
    console.log('OK');
  }

</script>

脚本&#39; widget_init.js&#39;如果尚未加载jQuery,则应该加载它。

我有这个脚本&#39; widget_init.js&#39;:

function load_script_jquery(){
  if (typeof jQuery == 'undefined') {  
    var jq = document.createElement('script'); jq.type = 'text/javascript';
    jq.src = '/path/to/js/jquery.min.js';
    document.getElementsByTagName('head')[0].appendChild(jq);
  } 
  else {

  }

}

load_script_jquery();

// some other code

问题是它不会等待加载jQuery,它会显示如下错误:

<script type="text/javascript">
  if (typeof jQuery == 'undefined') {  
    console.log('ERROR: NOT LOADED');  // NOT LOADED
  }
  else{
    console.log('OK'); // NEVER GOES HERE
  }

</script>

我试过这个也没有任何影响:

document.write('<script src="/path/to/js/jquery.min.js" type="text/javascript"><\/script>');

如何等到jQuery加载以便我可以使用它?

2 个答案:

答案 0 :(得分:2)

附加jQuery脚本的代码将附加 后面的<script>代码段进行检查。这就是.appendChild的工作原理

  

Node.appendChild()方法将节点添加到指定父节点的子节点列表的 end

来源: https://developer.mozilla.org/en-US/docs/Web/API/Node.appendChild(强调我的)

以下两个选项可以解决这个问题:

如果您可以在页面上插入HTML

您可以使用HTML5 Boilerplate中的此片段。它将检查另一个脚本是否已经加载了jQuery,如果没有,将加载它内联。

<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.11.2.min.js"><\/script>')</script>

在依赖它的脚本之前,将它放在头部或身体标签中。

如果您需要在Javascript源中动态加载

按照this tutorial

中的说明操作
(function () {

    function loadScript(url, callback) {

        var script = document.createElement("script")
        script.type = "text/javascript";

        if (script.readyState) { //IE
            script.onreadystatechange = function () {
                if (script.readyState == "loaded" || script.readyState == "complete") {
                    script.onreadystatechange = null;
                    callback();
                }
            };
        } else { //Others
            script.onload = function () {
                callback();
            };
        }

        script.src = url;
        document.getElementsByTagName("head")[0].appendChild(script);
    }

    loadScript("https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function () {

         //jQuery loaded
         console.log('jquery loaded');

    });


})();

答案 1 :(得分:1)

你需要回调函数,在成功加载jquery之后:

var loadJS = function(url, cb) {
        var script_tag = document.createElement('script');
        script_tag.setAttribute("type", "text/javascript");
        script_tag.setAttribute("src",
            url);
        if (script_tag.readyState) {
            script_tag.onreadystatechange = function() { // For old versions of IE
                if (this.readyState == 'complete' || this.readyState == 'loaded') {
                    cb();//calling callback
                }
            };
        } else { // Other browsers
            script_tag.onload = cb;//calling callback function
        }
        (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
    };

只需使用jquery库路径和回调函数引用调用此函数:

loadJS(hostUrl + "/js/libraries/jquery.js", callback);