【发布时间】:2011-01-11 13:31:31
【问题描述】:
我是这个 chrome 扩展插件开发的新手。我正在使用这个 chrome 扩展开发一个新的插件。
我的要求是在没有该 js 文件时将 jquery.js 文件加载到内容脚本中(例如:我正在检查 jquery.js 文件、fancybox.js 文件,如果不存在则加载这些文件。 )
当我在内容脚本中实现这个逻辑时,它正在加载 jquery.js 文件。之后它在内容脚本中不起作用。它显示 $(or) jQuery 未定义。每次加载,但不在内容脚本中执行。
这是我实现的代码。
document.getElementById('someid').onclick = loadJs();
function loadJS() {
if(tyof jQuery == undefined || tyof jQuery != 'function' )
{
var jqscript = document.createElement('script');
jqscript.type = 'text/javascript';
jqscript.async = true;
// Src of the script
jqscript.src = "......url to jquery.js file..............";
// Check whether script is loaded or not
jqscript.onload=function(){
if ((!this.readyState || this.readyState == "loaded" || this.readyState == "complete")) {
console.log("Script loaded - ");
// It is showing error here
alert(typeof jQuery);
}
};
// Get the document header
var head = document.getElementsByTagName('head')[0];
// Add script to header - otherwise IE complains
head.appendChild(jqscript);
}
}
请就此提出建议。
谢谢。
【问题讨论】:
-
如果你想让人们回答你的问题,你应该努力正确地格式化你的问题和代码。
-
你在那里称“内容脚本”有很多不同的东西。从您的代码看来,您正在尝试将 jquery 从内容脚本注入到父文档。如果您希望它在此之后也能在内容脚本中工作,那么它不会,因为内容脚本无权访问父文档变量。您能否重写您的问题并将内容脚本与父文档概念分开? (还有 0% 的比例是怎么回事?)
标签: jquery google-chrome-extension