【问题标题】:How to include jquery.js in another js file?如何将 jquery.js 包含在另一个 js 文件中?
【发布时间】:2011-07-31 11:17:20
【问题描述】:

我想在 myjs.js 文件中包含 jquery.js。我为此编写了下面的代码。

  var theNewScript=document.createElement("script");
  theNewScript.type="text/javascript";
  theNewScript.src="http://example.com/jquery.js";
  document.getElementsByTagName("head")[0].appendChild(theNewScript);
  $.get(myfile.php);

第 5 行显示一个错误,即“$ 未定义”。我想包含 jquery.js,然后想在 myjs.js 文件中调用 $.get() 函数。我怎样才能做到这一点? 请帮帮我

【问题讨论】:

标签: javascript jquery include


【解决方案1】:

以编程方式在文档头部添加脚本标签并不一定意味着该脚本立即可用。您应该等待浏览器下载该文件,解析并执行它。某些浏览器会为您可以连接逻辑的脚本触发onload 事件。但这不是一个跨浏览器的解决方案。我宁愿“投票”让特定符号可用,如下所示:

var theNewScript = document.createElement("script");
theNewScript.type = "text/javascript";
theNewScript.src = "http://example.com/jquery.js";
document.getElementsByTagName("head")[0].appendChild(theNewScript);
// jQuery MAY OR MAY NOT be loaded at this stage
var waitForLoad = function () {
    if (typeof jQuery != "undefined") {
        $.get("myfile.php");
    } else {
        window.setTimeout(waitForLoad, 1000);
    }
};
window.setTimeout(waitForLoad, 1000);

【讨论】:

  • 哪些浏览器不支持 onload 事件?即使在 IE 7 等较旧的浏览器中,它也能正常工作。
  • 我已经阅读(但未亲自确认)脚本标签的onload 事件在壁虎、歌剧等中有效,而对于 IE,您需要挂钩 onreadystatechange。见unixpapa.com/js/dyna.htmlblog.lexspoon.org/2009/12/…
  • 确实,调用事件处理程序的方式取决于浏览器。我对现代浏览器使用 addEventListener,对旧 IE 使用 attachEvent,效果很好。
【解决方案2】:

问题是脚本不会立即加载,脚本文件需要一些时间才能下载到您的页面并执行(如果使用 jQuery 来定义 $)。

我建议您使用HeadJS。那么你可以这样做:

head.js("/path/to/jQuery.js", function() {
   $.get('myfile.php');
});

【讨论】:

    【解决方案3】:

    简单的答案,不要。 jQuery 文件 对入侵者非常敏感,所以不要 尝试。将其他文件加入 jQuery 文件经常会导致JS中的错误 控制台,PLUS jQuery 未初始化 直到文件加载到 main 文件。

    对不起,从头开始。不太清楚你在做什么。

    试试这个:

    var s = document.createElement('script');
    s.type = 'text/javascript';
    s.async = true;
    s.src = 'http://domain.com/jquery.js';
    (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(s);
    

    【讨论】:

      【解决方案4】:

      我之前用过这段代码,它成功了:

      var t=document;
      var o=t.createElement('script');
      o=t.standardCreateElement('script');
      o.setAttribute('type','text/javascript');
      o.setAttribute('src','http://www.example.com/js/jquery-1.3.2.js');
      t.lastChild.firstChild.appendChild(o);
      

      【讨论】:

        猜你喜欢
        • 2011-06-05
        • 1970-01-01
        • 2012-02-15
        • 1970-01-01
        • 1970-01-01
        • 2013-04-23
        • 1970-01-01
        • 2011-11-24
        相关资源
        最近更新 更多