2012-07-03 41 views
2

我正在研究需要訪問jquery-ui以及jquery min的書籤。當然關心的是頁面可能已經加載了jQuery並且應該避免衝突。在Bookmarklet中加載jQuery和jQuery UI(如果它們尚未加載)

使用本Alman的代碼處http://benalman.com/code/javascript/jquery/jquery.ba-run-code-bookmarklet.js發現我已經能夠優雅地介紹jQuery和在UI砍死加載以及但似乎與延遲問題和jQuery UI還沒有準備好去正確...

是否有更好的方式來處理在執行實際代碼之前按順序加載兩個腳本?

(function(window, document, jQuery, req_version, callback, callback_orig, parent, script){ 

    if (!window[jQuery] || req_version > window[jQuery].fn.jquery) { 
    parent = document.documentElement.childNodes[0]; 
    script = document.createElement('script'); 
    script.type = 'text/javascript'; 
    script.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js'; 
    parent.appendChild(script); 

    callback_orig = callback; 
    callback = function($, L) { 
     '$:nomunge, L:nomunge'; 
     $(script).remove(); 
     callback_orig($, L); 
    }; 
    } 

    if (typeof jQuery.ui == 'undefined'){ 
    parent = document.documentElement.childNodes[0]; 
    scriptui = document.createElement('script'); 
    scriptui.type = 'text/javascript'; 
    scriptui.src = 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.7/jquery-ui.js'; 
    parent.appendChild(scriptui); 
    alert('Loading your matches...'); 
    } 

    (function loopy($){ 
    '$:nomunge'; // Used by YUI compressor. 

    ($ = window[jQuery]) && req_version <= $.fn.jquery 
     ? callback(parent ? $.noConflict(1) : $, !!parent) : setTimeout(loopy, 50); 
    })(); 

})(window, document, 'jQuery', '1.3.2', 

function($,L) { 
    '$:nomunge, L:nomunge'; 

<all the jquery stuff goes here> 

有在Using jQuery UI in a Bookmarklet一個類似的問題有着深入的答案,但我一直無法從CoffeeMarklet翻譯這個「標準」 JS。

回答

3

查看我的要點 - 這是一個用於加載jQuery的小書籤模板,但您可以指定其他腳本和css在執行前加載。

https://gist.github.com/2897748

你初始化像這樣。

編輯:如果您需要加載依賴關係,您可以創建一個數組並根據不同的條件將其推入其中。

var jsDependencies = []; 

// This will only load jQuery UI if it does not exist already. 
// Of course if you rely on the page's copy, you have to do some 
// more advanced things to check for versions and whatnot. 
if(!window.jQuery || !window.jQuery.ui){ 
    jsDependencies.push('http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js'); 
} 

var MyBookmarklet = MyBookmarklet || new Bookmarklet({ 
    // debug: true, // use debug to bust the cache on your resources 
    css: ['/my/style.css'], 
    js: jsDependencies, 
    // jqpath: '/my/jquery.js', // defaults to google cdn-hosted jquery 
    ready: function(base) { // use base to expose a public method 
    base.init = function(){ 
     // doStuff(); 
    }  
    base.init(); 
    } 
}); 
+0

啊,說得太快。我查看的頁面已經加載了UI並添加了js:['http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js'],正在生成錯誤:arr未定義,第74行(git pub的63) –

+0

糟糕。我很抱歉。 '''arr'''應該改成'''scripts'''。我已經更新了要點。 –

+0

此外,請確保您使用'https://','http://'或'//'。最後一個是協議相關的url。該腳本需要一個完全合格的URI來加載內容。 –