2010-04-29 40 views
3

在userscript中提供必要的新版本jQuery(1.4.2)的最佳策略是什麼,它修改了一個已經具有舊版本jQuery(1.3.1)的頁面?在GreaseMonkey中使用jQuery 1.4,而原始頁面使用jQuery 1.3(不同版本)?

最好原始頁面繼續使用'$'符號,而在我的腳本中它使用由jquery.noConflict()指定的別名。

根據對this question的回答,任何一個希望加載的額外版本都應放置在原始腳本標記之上。這是我有點困惑,因爲我有印象GreaseMonkey頁面加載後執行腳本?

編輯:一個想法是在userscript,追加一個腳本標籤的jQuery 1.4.2,設置別名,然後再追加一個腳本標記爲1.3.1,以不打破原有頁面的代碼,它使用1.3.1功能。

var code142 = function() { 
    gj = jQuery.noConflict(true); 
    alert("142..."); 
    alert(gj); // check if the dollar (jquery) function works 
    alert(gj().jquery); // check jQuery version 
} 

var script = document.createElement("script"); 
script.src = 'http://code.jquery.com/jquery-1.4.2.min.js' 
document.documentElement.appendChild(script); 


// assign jquery object alias and run code that uses 1.4.2 there 
var script = document.createElement("script"); 
script.textContent = '(' + code142.toString() + ')();'; 
document.documentElement.appendChild(script); 

/* The following is perhaps redundant, see EDIT 2 for more info 

// add jquery 1.3.1 (again) 
var script = document.createElement("script"); 
script.src = 'http://code.jquery.com/jquery-1.3.1.min.js' 
document.documentElement.appendChild(script); 

*/ 

但是,這將需要加載jQuery庫每頁3次。有沒有更好的方法?

編輯2:儘管GM腳本已經提供了1.4.2副本,但似乎原始頁面仍然可以使用其1.3.1副本,只要我使用新別名,它們就可以共存(gj)來引用code142()中的1.4.2 jQuery對象。

如果沒有其他問題出現,那麼這將是我的解決方案。我希望對其他可能遇到這個問題的人有用。

回答

2

I believe this is what you're looking for

只要您沒有做任何複雜的事情,並且不需要最新版本,請按照鏈接中的模式進行操作。

它再次包含之前檢查jQuery是否加載(typeof unsafeWindow.jQuery == 'undefined')。 「簡單」部分只是意味着你在1.3和1.4中工作,可能是1.2.6?如果是這種情況,只要加載了哪個版本就無關緊要了。 (除非它是一個非常舊網站,然後check that the functions you're using so way back in jQuery core,但這是不太可能)

+0

嗨。這種情況下需要最新版本,因爲原始頁面上的舊版本不支持我想用於我的用戶腳本的一些功能。 – Dan7 2010-04-29 16:55:13

相關問題