如何在另一个js文件中包含jquery.js? [英] How to include jquery.js in another js file?

查看:142
本文介绍了如何在另一个js文件中包含jquery.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行显示$ not defined错误。我想包含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);

这篇关于如何在另一个js文件中包含jquery.js?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆