如何在另一个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()函数。 我怎样才能做到这一点? 请帮我

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

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

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

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

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

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

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