How to Load jQuery Conditionally


This article is about How to Load jQuery Conditionally Many developers like to link to an externally hosted jQuery library, like for example Google’s jQuery library but the problem with linking to an external jQuery library is that they can be a bit unreliable. If for some reason there are any issues with the server, the script may not be able to be accessed and your jQuery code won’t work.

HTML5’s boilerplate uses a really cool conditional statement that will load a local jQuery library on the occasion that, for whatever reason, your external library isn’t loading or working correctly. Check it out:

<!– Grab Google CDN jQuery. fall back to local if necessary –> <script src=”//ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js”></script> <script> window.jQuery && document.write(‘<script src=”js/jquery-1.4.2.min.js”><\/script>’) </script>

Of course, you’ll need to insert your own path to wherever your local jQuery files are located (instead of ‘<script src=”js/jquery-1.4.2.min.js”></script>’), but this is a very simple way to make sure that your jQuery library always loads.

// Conditionally Load jQuery (javascript)
// Source: https://gist.github.com/gists/902090/
var init, maybeLoadJq;

init = function() {
jQuery(document).ready(function() {
alert(‘Your Code Here’);
});
};

maybeLoadJq = function() {
var jQ;
if (!(typeof jQuery !== “undefined” && jQuery !== null)) {
jQ = document.createElement(‘script’);
jQ.type = ‘text/javascript’;
jQ.onload = jQ.onreadystatechange = init;
jQ.src = ‘//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js’;
return document.body.appendChild(jQ);
} else {
return init();
}
};

if (window.addEventListener) {
window.addEventListener(‘load’, maybeLoadJq, false);
} else if (window.attachEvent) {
window.attachEvent(‘onload’, maybeLoadJq);
}


 

Leave a Reply

Your email address will not be published. Required fields are marked *