How to embed Javascript widget that depends on jQuery into an unknown environment

After reviewing some answers and pointers, and finding some helpful jQuery hackers, I ended up with something like the following:

(function(window, document, version, callback) {
    var j, d;
    var loaded = false;
    if (!(j = window.jQuery) || version > j.fn.jquery || callback(j, loaded)) {
        var script = document.createElement("script");
        script.type = "text/javascript";
        script.src = "";
        script.onload = script.onreadystatechange = function() {
            if (!loaded && (!(d = this.readyState) || d == "loaded" || d == "complete")) {
                callback((j = window.jQuery).noConflict(1), loaded = true);
        (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script);
})(window, document, "1.3", function($, jquery_loaded) {
    // Widget code here

This will load jQuery if it’s not already loaded and encapsulates it in the callback so it doesn’t conflict with a pre-existing jQuery on the page. It also checks that a minimum version is available or else loads a known version — in this case, v1.3. It sends a boolean value to the callback (my widget) on whether or not jQuery was loaded in case there are any triggers needed to be made. And only after jQuery is loaded does it call my widget, passing jQuery into it.

Leave a Comment