Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does jQuery load twice in my GreaseMonkey Script

for some reason my Firefox4+GreaseMonkey Script loads jQuery twice. I copy'n'pasted the following snippet, the "test" alert shows twice.

Regards

var $;

// Add jQuery
(function(){
    if (typeof unsafeWindow.jQuery == 'undefined') {
        var GM_Head = document.getElementsByTagName('head')[0] || document.documentElement,
            GM_JQ = document.createElement('script');

        GM_JQ.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js';
        GM_JQ.type = 'text/javascript';
        GM_JQ.async = true;

        GM_Head.insertBefore(GM_JQ, GM_Head.firstChild);
    }
    GM_wait();
})();

// Check if jQuery's loaded
function GM_wait() {
    if (typeof unsafeWindow.jQuery == 'undefined') {
        window.setTimeout(GM_wait, 100);
    } else {
        $ = unsafeWindow.jQuery.noConflict(true);
        letsJQuery();
    }
}

// All your GM code must be inside this function
function letsJQuery() {
    alert("test");
}
like image 400
Fabian Zeindl Avatar asked May 03 '11 23:05

Fabian Zeindl


1 Answers

This is probably because the target page is loading frames or iframes.

Add these lines to the top of the code-portion of your script:

if (window.top != window.self)  //-- Don't run on frames or iframes
    return;


Also, if you are just using FF + GM, don't bother with all that rigamarole to load jQuery. GM now works with the later jQuery versions.

Just add a line like:

// @require http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js

into your script's metadata block. jQuery will be copied once onto your local machine and run from there -- eliminating what can sometimes be a few seconds delay in your script's runtime.

And such scripts can run in Chrome, if you use one of the GM-emulating extensions like TamperMonkey.

like image 114
Brock Adams Avatar answered Nov 09 '22 23:11

Brock Adams