How to include jquery.js in another js file?(如何将 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);
这篇关于如何将 jquery.js 包含在另一个 js 文件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将 jquery.js 包含在另一个 js 文件中?


基础教程推荐
- Bokeh Div文本对齐 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01