【问题标题】:include jquery in js file在 js 文件中包含 jquery
【发布时间】:2012-07-14 05:28:47
【问题描述】:

我正在开发 chrome 扩展,它是一个简单的扩展,它调用 background.js 文件来完成简单的工作。在 background.js 我想包含 jquery.js 文件来调用 ajax 函数。但我无论如何都找不到在 background.js 中包含 jquery.js。可以这样做吗?

你知道,扩展调用 background.js,它不调用包含 background.js 的 php 或 html 文件,所以我不能使用任何涉及 php 或 html 的东西

提前谢谢....

【问题讨论】:

  • 获取 jquery 内容,并在 background.js 中添加文本
  • 我认为这是最后的选择,还有其他解决方案吗?
  • 为什么是最后一个选项?这比创建新节点提供了更好的性能。
  • 我知道,但是当这样做时,它会使代码变得有点静态。我认为还有另一种解决方案可以包含

标签: javascript jquery ajax google-chrome include


【解决方案1】:

听起来您使用的是 manifest_version 2,这意味着您只需将 path-to-jquery.js 添加到 background.scripts 数组即可。

"background": {
    "scripts": ["jquery.js", "background.js"]
}

这些文件都一起加载到生成的页面中,因此它们访问相同的全局范围——这意味着您可以像往常一样使用jQuery。

【讨论】:

    【解决方案2】:

    来吧:

    var jQueryElement=document.createElement('script');
    jQueryElement.type = 'text/javascript';
    jQueryElement.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js';
    document.getElementsByTagName('head')[0].appendChild(jQueryElement);
    

    您必须将所有内容放在 onload 事件处理程序中,否则即使 jQuery 尚未加载,其余的 JavaScript 仍将继续运行。

    var jQueryElement=document.createElement('script');
    jQueryElement.type = 'text/javascript';
    jQueryElement.onload = function () {
        alert('jQuery loaded');
    };
    jQueryElement.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js';
    document.getElementsByTagName('head')[0].appendChild(jQueryElement);
    

    【讨论】:

    • 正如我上面提到的,我们没有 php 或 html 文件
    • 如果找不到head标签怎么办,因为background.js在后台运行
    • 那么没有其他方法可以包含另一个 JavaScript 文件。这是的方法。您必须将 jQuery 复制并粘贴到源文件中。
    猜你喜欢
    • 2015-03-09
    • 1970-01-01
    • 1970-01-01
    • 2011-01-09
    • 1970-01-01
    • 2013-02-19
    • 2017-12-22
    • 1970-01-01
    • 2013-03-24
    相关资源
    最近更新 更多