Load jQuery Dynamically Thursday, May 7, 2009

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