如何将 jquery.js 包含在另一个 js 文件中?
我想在 myjs.js 文件中包含 jquery.js.我为此编写了下面的代码.
I want to include jquery.js in myjs.js file. I wrote the code below for this.
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() 函数.我怎样才能做到这一点?请帮帮我
There shows an error on the 5th line that is '$ not defined'. I want to include jquery.js and then want to call $.get() function in myjs.js file. How can I do this? Please help me
推荐答案
以编程方式在文档头部添加一个脚本标签并不一定意味着该脚本将立即可用.您应该等待浏览器下载该文件,解析并执行它.某些浏览器会触发 onload
事件,以便您可以在其中连接您的逻辑的脚本.但这不是一个跨浏览器的解决方案.我宁愿投票"让特定符号可用,如下所示:
Appending a script tag inside the document head programmatically does not necessarily mean that the script will be available immediately. You should wait for the browser to download that file, parse and execute it. Some browsers fire an onload
event for scripts in which you can hookup your logic. But this is not a cross-browser solution. I would rather "poll" for a specific symbol to become available, like this:
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);
相关文章