问题 如何在另一个js文件中包含jquery.js?


我想在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行显示“$ not defined”错误。我想包含jquery.js,然后想在myjs.js文件中调用$ .get()函数。我怎样才能做到这一点? 请帮帮我


9178
2018-04-07 08:00


起源

你为什么要在页面外使用$ .get()? - Calum
我想你应该说 $.get("myfile.php"); 代替 $.get(myfile.php);。 - Salman A
可能重复 检查是否已加载jquery,如果为false则加载它 - Ciro Santilli 新疆改造中心 六四事件 法轮功


答案:


以编程方式在文档头中附加脚本标记并不一定意味着脚本可用 立即。您应该等待浏览器下载该文件,解析并执行它。有些浏览器会触发 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);

11
2018-04-07 08:15



哪些浏览器不支持onload事件?即使在像IE 7这样的老式浏览器中,它也能正常工作。 - Christophe
我已阅读(但未经亲自确认) onload 脚本标签的事件在壁虎,歌剧等中工作,而对于IE,您需要挂钩 onreadystatechange。看到 unixpapa.com/js/dyna.html 和 blog.lexspoon.org/2009/12/... - Salman A
确实,调用事件处理程序的方式取决于浏览器。我为现代浏览器使用addEventListener,为旧IE使用attachEvent,工作得很好。 - Christophe


问题是脚本没有立即加载,脚本文件下载到页面并执行需要一些时间(在jQuery的情况下定义$)。

我建议你使用 HeadJS。然后你可以这样做:

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

4
2018-04-07 08:04



这个。解决了。所有。我的。问题。谢谢。 - Andres SK


简单的回答,不要。 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);

0
2018-04-07 08:04





我之前使用过这段代码,它起作用了:

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);

0
2018-04-07 08:06