我想寫一個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