在js文件中包含jquery

include jquery in js file

本文关键字:包含 jquery 文件 js      更新时间:2023-09-26

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

你知道,扩展名调用background.js,它不调用php或html文件,其中包括background.jss,所以我不能在php或html 中使用任何东西

提前感谢。。。。

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

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

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

开始吧:

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);