Does anybody know a way to detect if the jQuery library was loaded and if not append it and start a script as a fallback solution after it’s loaded to the DOM?
Here’s my script:
if (typeof jQuery == 'undefined') {
// if jQuery Library is not loaded
var script = document.createElement( 'script' );
script.type = 'text/javascript';
script.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js';
document.body.appendChild(script);
startScript();
} else {
// cool, jQuery Library is loaded
startScript();
}
function startScript() {
$.noConflict();
jQuery(document).ready(function($){
.... // my jquery code
});
}
Of course, above appends jQuery correctly but doesn’t do anything because the script starts immidiately after appending. Any hint on this?
I appreciate any answer. Thanks!
You’re fine except, as you said, that you can’t call
startScriptimmediately after appending the newscriptelement. Instead, do asetTimeoutloop:Where
maybeStartlooks like this (not within the body of theif, function declarations aren’t valid there):That checks if jQuery is loaded and, if not, waits a 10th of a second and checks again. When jQuery is found, it calls your
startScript.You might want to put a time limit in there (in case jQuery never loads, so you don’t loop forever).
Alternately, you can hook a “load”-style event on the
scriptelement, but the mechanics of it vary from browser to browser. On some browsers it’s justloadas with, say, animgelement; on IE (at least older versions), you have to usereadystatechange, and on some versions of IE both work. So you have to keep a flag so you know whether you’ve fired off your script, etc., and…well, the above is less complicated in the case where you know the script creates a well-known global symbol (as is the case with jQuery).