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

Javascript 如何在另一个js文件中包含jquery.js?,javascript,jquery,include,Javascript,Jquery,Include,我想在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);

我想在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行显示一个错误,即“$notdefined”。我想包括jquery.js,然后在myjs.js文件中调用$.get()函数。我该怎么做?
请帮助我

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

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

head.js("/path/to/jQuery.js", function() {
   $.get('myfile.php');
});
简单的回答,不要。jQuery文件 对入侵者非常敏感,所以不要 尝试将其他文件加入jQuery 文件通常会导致JS中出现错误 控制台,加上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);

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

为什么要在页面之外使用$.get()?我想您的意思是说
$.get(“myfile.php”)
而不是
$.get(myfile.php)。哪些浏览器不支持onload事件可能重复?即使在像IE 7这样的旧浏览器中,它也能正常工作。我读过(但没有亲自确认)脚本标记的
onload
事件在gecko、opera等浏览器中工作,而在IE中,你需要钩住
onreadystatechange
。请参阅,调用事件处理程序的方式确实取决于浏览器。我对现代浏览器使用addEventListener,对旧IE使用attachEvent,效果很好。