Search code examples
javascriptjquerybookmarklet

Checking if jQuery has been loaded in bookmarklet


I am using the following piece of code to make sure that jQuery has been loaded in page before I execute the main body of javascript in my bookmarklet. Is there any chance this code fails to load jQuery properly in any browser?

if (!window.jQuery) {
    var script = document.createElement("script");
    script.src = "//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js";
    script.onload = function () {
        foo();
    };
    document.head.appendChild(script);
} else {
    foo();
}

function foo() {
    // bookmarklet code goes here
}

Solution

  • Is there any chance this code fails to load jQuery properly in any browser?

    Not unless the page in question was loaded from a local resource rather than via http / https. In that case, the protocol-relative URL will fail.

    You'll want to reverse the order in which you set the src and onload properties, though; if the resource is in cache, the event can be fired before you hook up the handler (JavaScript in browsers is single-threaded other than Web Workers, but browsers are not single-threaded).

    Also, there's no need to wrap an additional function around foo:

    if (!window.jQuery) {
        var script = document.createElement("script");
        script.onload = foo;
        script.src = "//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js";
        document.head.appendChild(script);
    } else {
        foo();
    }
    
    function foo() {
        // bookmarklet code goes here
    }
    

    If you want to handle the protocol issue so it works with file: URLs and such, that's easy enough to do:

    if (!window.jQuery) {
        var protocol = location.protocol;
        if (protocol !== "http:" && protocol !== "https:") {
            protocol = "http:";
        }
        var script = document.createElement("script");
        script.onload = foo;
        script.src = protocol + "//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js";
        document.head.appendChild(script);
    } else {
        foo();
    }
    
    function foo() {
        // bookmarklet code goes here
    }