Load jQuery Dynamically

Sometimes you have to load jQuery, but you don’t know if it has already been referenced somewhere else in the website. 

This tends to happen if you have a custom web control, delivered in an assembly, that relies on jQuery.

This code has been ripped out of my application, and may have a typo or three, but it gives you the general idea.

 

var jQueryScriptOutputted = false;
function initJQuery() {
    
    //if the jQuery object isn't available
    if (typeof(jQuery) == 'undefined') {
    
    
        if (! jQueryScriptOutputted) {
            //only output the script once..
            jQueryScriptOutputted = true;
            
            //output the script (load it from google api)
            document.write("<scr" + "ipt type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js\"></scr" + "ipt>");
        }
        setTimeout("initJQuery()", 50);
    } else {
                        
        $(function() {  
            //do anything that needs to be done on document.ready
        });
    }
            
}
initJQuery();

 

More later - joel

16 Comments

  • Yea - that's what you should do if you are writing code in the actual application itself. This example is more for code written in a custom control which may be used in ANY application, and you don't know if jQuery is actually loaded yet.

  • I'd prefer an error message that states that jQuery is not loaded and that your controls depend on jQuery. It's up to the developer then where and how he seems fit to load jQuery.

    With your approach I could end up with a hundred initJQuery(){...} method declarations in my page. Which wouldn't work all together.

    Cheers,
    Wes

  • Good point.
    What I did was put that code into a RegisterStartUpScript with a key, so that wasn't an issue.

  • Thanks for this great example, I was looking for something just like for an embedded widget distribution system I'm working on.

  • This is exactly what i was looking for. Not only that it checks if jQuery is already loaded, but it loads it dynamically too from Google API. This is a great help since we have lots of customers that load a script from our server and i wanted to add a jQuery reference. My option was to output jQuery inside our script and let it load very very slow, or find a way to include the code from Google API. Of course there's the Google way to load it, but that pretty much means i have to load Google's codes too and i wouldn't be saving much. You just helped me save 90% of our bandwidth with this.

  • thank u much, worked fine.

  • Thanks, you saved my day ;)

  • perfect script,
    i really need this script.
    Thanks for sharing

  • This is nice and all, except for it doesn't work if you're trying to lazy load jquery, i.e. loading jquery after the page has been been rendered. Let's say you want to load jquery after the page has loaded, based on some event, like an element click. You can't use document.write in that case and need to create a script element node and attach it to the HEAD.

    Other than that, not a bad little function.

  • Probably a stupid question, but I have to learn stuff the first time once, so go easy on me. While researching this exact subject, over the past 30 min or so, I've come across two examples where the word "script" is split into two strings that are then concatenated. i.e."<scr" + "ipt[...]" What's the logic behind this?

    Thanks in advance,

    -PC

  • I've made a slight tweak to your code, as my control might be loaded multiple times in the same page, I didn't want the jQueryScriptOutputted value being reset:

    var jQueryScriptOutputted = ((typeof(jQueryScriptOutputted) == 'undefined') ? false : true);

  • Load jquery dynamically.. Nice :)

  • Load jquery dynamically.. He-he-he :)

  • A timeout could also be added just in case the jquery.min.js file is not available - some ideas:

    load = {

    // dynamically load any javascript file.
    getScript: function (filename) {
    var script = document.createElement('script')
    script.setAttribute("type", "text/javascript")
    script.setAttribute("src", filename)
    if (typeof script != "undefined")
    document.getElementsByTagName("html")[0].appendChild(script)
    },

    waitjQuery: function (time_elapsed, callbackJQueryReady) {

    /* Continually polls for jQuery library. */
    if (typeof $ == "undefined") {
    if (time_elapsed <= 5000) {
    setTimeout("load.waitjQuery(" + (time_elapsed + 200) + ")", 200);
    } else {
    alert("Timed out while loading jQuery.")
    }
    } else {

    //JQuery has finally loaded..... so
    //Call the callbackReady function passed

    }
    }

    };

  • Thanks, this really helps allot

  • Load jquery dynamically.. Neat :)

Comments have been disabled for this content.