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

Published Thursday, May 7, 2009 4:05 PM by joelvarty
Filed under: , ,

Comments

# re: Load jQuery Dynamically

Friday, May 8, 2009 8:50 AM by joelvarty

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.

# re: Load jQuery Dynamically

Friday, May 8, 2009 11:16 AM by webbes

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

# re: Load jQuery Dynamically

Friday, May 8, 2009 11:22 AM by joelvarty

Good point.  

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

# re: Load jQuery Dynamically

Tuesday, July 28, 2009 7:39 PM by Lev

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

# re: Load jQuery Dynamically

Thursday, August 27, 2009 12:35 PM by Alex S

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.

# re: Load jQuery Dynamically

Monday, August 31, 2009 9:02 AM by e-turhan

thank u much, worked fine.

# re: Load jQuery Dynamically

Friday, November 27, 2009 11:31 AM by Simon

Thanks, you saved my day ;)

# re: Load jQuery Dynamically

Thursday, January 14, 2010 1:04 AM by ogi

perfect script,

i really need this script.

Thanks for sharing

# re: Load jQuery Dynamically

Tuesday, March 2, 2010 2:14 PM by mark

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.

# re: Load jQuery Dynamically

Wednesday, October 20, 2010 2:49 PM by Planecrash

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

# re: Load jQuery Dynamically

Friday, January 21, 2011 7:07 PM by Bob Davies

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);

# re: Load jQuery Dynamically

Tuesday, April 19, 2011 6:24 PM by weblogs.asp.net

Load jquery dynamically.. Nice :)

# re: Load jQuery Dynamically

Friday, May 6, 2011 8:30 AM by weblogs.asp.net

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

# re: Load jQuery Dynamically

Sunday, May 15, 2011 5:47 AM by Mozzoh

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

       }

   }

};

# re: Load jQuery Dynamically

Saturday, June 4, 2011 6:57 PM by Lex

Thanks, this really helps allot

# re: Load jQuery Dynamically

Sunday, June 19, 2011 10:03 PM by weblogs.asp.net

Load jquery dynamically.. Neat :)