我想写一个jquery包装,这将允许新的用户脚本,我正在写函数与旧的,在铬和Firefox中,并运行jquery。我以前的用户使用Joan Piedra的方法(http://joanpiedra.com/jquery/greasemonkey/),但这在Chrome中不起作用,因为Chrome不支持unsafewindow。
所以我找到了Erik Vold在Chrome中运行jQuery的方法(http://erikvold.com/blog/index.cfm/2010/6/14/using-jquery-with-a-user-script),但是它在firefox和现有的用户脚本中并没有任何作用。
我决定尝试修改Erik的脚本来首先搜索jquery,然后只在jquery未定义时插入脚本标记。如果存在jquery,它不会插入jquery脚本标记,但只是运行jquery回调(在没有冲突模式下,因为我期望它在一个页面上运行并且使用scriptaculous)。
我的问题(首先,我肯定给出了我所需要的数量)在addJQuery中的if/else语句中:在语句的else部分(其中jquery对象不应该是'undefined'),jquery对象仍然是实际上'未定义',所以我得到错误,'$'在回调运行时未定义。
Erik的原始代码附加了一个事件监听器来加载jquery脚本,但我不知道如何在事件中这样做jquery已经存在但未必加载(我尝试将事件监听器附加到窗口,文档,document.head和document.body并没有任何工作。)
我也尝试过使用window.setTimeout,但我不能重复多次,具有相同的结果($是undefined )
我还会提到,在我知道jQuery不在其中的情况下,该脚本确实成功添加了脚本标记,并且我已将该事件监听器附加到脚本中,而且我仍然得到$未定义的错误。
所以我现在完全处于亏损状态。我无法检测到jQuery,即使看起来我有,我也无法运行代码,即使看起来像我,它仍然会中断。
function addJQuery(callback) {
if(typeof jQuery == 'undefined'){
var libsrc = "http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js";
var dochead = head = document.getElementsByTagName('head')[0];
var jqscript = document.createElement("script");
jqscript.setAttribute("type","text/javascript");
jqscript.setAttribute("src", libsrc);
// append script tag as first element in the head
dochead.insertBefore(jqscript, head.childNodes[0]);
jqscript.addEventListener('load', function(){
var runscript = document.createElement("script");
// force no conflict mode allowing $
runscript.textContent = "jQuery.noConflict(); (function($) { $(function() {" + callback.toString() + "}); })(jQuery);";
document.getElementsByTagName('head')[0].appendChild(runscript);
callback();
}, false);
}
else{
// jquery is still undefined?!?!?!?!
var runscript = document.createElement("script");
runscript.setAttribute("type", "text/javascript");
// force no conflict mode allowing $
runscript.textContent = "jQuery.noConflict(); (function($) { $(function() {" + callback.toString() + "}); })(jQuery);";
document.getElementsByTagName('head')[0].appendChild(runscript);
callback();
}
}
function main() {
alert($); // check if the dollar (jquery) function works
alert($().jquery); // check jQuery version
}
// load jQuery and execute the main function
addJQuery(main);
谢谢,我试了几次这种方法,并没有得到它的工作。无论如何,我也无法使用unsafeWindow并使其在Chrome中运行。 – 2011-05-11 19:50:58