2011-04-07 44 views
10

我想在myjs.js文件中包含jquery.js。我为此写了下面的代码。如何将jquery.js包含在另一个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()函数。我怎样才能做到这一点? 请帮我

+0

为什么你想要在页面之外使用$ .get()? – Calum 2011-04-07 08:05:50

+0

我假设你打算说'$ .get(“myfile.php”);'而不是'$ .get(myfile.php);'。 – 2011-04-07 08:22:43

+0

[检查jquery是否已被加载,然后加载它如果为false]可能的重复(http://stackoverflow.com/questions/1828237/check-if-jquery-has-been-loaded-then-load-it-if - 假) – 2014-06-01 08:25:33

回答

10

追加的文件头中的脚本标签编程并不一定意味着该脚本将可用立即。您应该等待浏览器下载该文件,解析并执行它。某些浏览器会触发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); 
+0

哪些浏览器不支持onload事件?即使在IE 7之类的旧版浏览器中,它也能正常工作。 – Christophe 2013-03-05 17:56:29

+1

我已阅读(但未亲自确认)脚本标记的'onload'事件适用于壁虎,歌剧等,而对于IE,您需要挂钩'onreadystatechange'。请参阅http://unixpapa.com/js/dyna.html和http://blog.lexspoon.org/2009/12/detecting-download-failures-with-script.html – 2013-03-05 18:11:06

+0

确实,您称之为事件的方式处理程序取决于浏览器。我使用现代浏览器的addEventListener和旧IE的attachEvent,工作得很好。 – Christophe 2013-03-05 18:15:53

4

问题是脚本不能立即加载,需要一段时间才能将脚本文件下载到您的页面并执行(如果是jQuery来定义$)。我想推荐你使用HeadJS。那么你可以这样做:

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

这个。解决了。所有。我的。问题。谢谢。 – andufo 2011-12-12 06:40:42

0

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

对不起,划伤了。不知道你在做什么。

试试这个:

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

我之前用这个代码,它的工作:

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); 
相关问题