写浏览器插件需要动态加载jquery进来,发现在动态加载jquery的script标签的load事件中执行用户自己的代码时报错,找不到jquery。
原因分析:动态加载的script标签append到body后执行环境为当前浏览器环境,而load回调函数中代码的执行环境为插件本身
解决方法:用户自身的代码页用script标签加载字符串的形式append到body上面
// @name plugin
// @version 1.0
// @author frankqian
// @description helper
// @namespace http://use.i.E.your.homepage/
// @match http://a.b.com/cgi-bin/menucgi
// @run-at document-end
// ==/UserScript==
var load, execute, loadAndExecute;
load=function(src,success,error){
var script=document.createElement("script");
script.setAttribute("src",src);
success!=null&&script.addEventListener("load",success);
error!=null&&script.addEventListener("error",error);
document.body.appendChild(script);
return script
};
//nserts a function or string of code into the document and executes it. The functions are converted to source code before being inserted, so they lose their current scope/closures and are run underneath the global window scope.
execute=function(success){
var b,c;
typeof success=="function"?b="("+success+")();":b=success;
c=document.createElement("script"),c.textContent=b,document.body.appendChild(c);
return c
};
loadAndExecute=function(src,success,error)
{
return load(src,function(){
return execute(success);
},error)
};
loadAndExecute("//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js", function() {
// your code here
});