Checking if JQuery is loaded, and load it if it isn't

  • posted by mark
  • on Dec. 12, 2013
A scenario cropped up recently where I was developing a portable extension module in PHP, designed to be used as a drop in component on various sites, and I came across an issue I've hit a few times before. The problem is, the extension I was developing relied heavily on JQuery, but we couldn't guarantee that JQuery was installed in every site the extension would be used on. Sure, there's a couple of easy ways around this. We could have simply brought up a warning message, stating that JQuery was required for use with this plugin and requiring the site owner to install it in their theme. Alternatively we could have just included JQuery in the extensions headers, but this would have had the potential to overwrite any already included version, and as anyone who has ever dealt with JQuery version conflicts between other components supporting different versions knows .. that can be one massive headache. So the solution was to first check if JQuery is included, and load it if it isn't. This was achieved with the following code snippet, used in conjunction with a previous code snippet I've posted to dynamically load scripts .. which can be obtained here - Dynamically Loading Javascript After a Page Load.
function onJQInit() {
    alert("Loaded JQuery!");
}

if (typeof jQuery == 'undefined') {  
    // jQuery is not loaded .. load it
    loadScript("http://code.jquery.com/jquery-1.10.1.min.js", function() {
        setTimeout(function() {
            if(typeof jQuery != 'undefined')
                onJQInit();
        }, 100);
    });
} else {
    onJQInit();
}
If you need a later version of JQuery or want to use your own hosted version, just change the URL when calling the loadScript function. Also it's worth remembering if you want to do this as soon as possible, you'll need to wait until after the page has loaded before executing the loadScript function ... otherwise document.body may not exist. Again, there's an example for this you can adapt at Dynamically Loading Javascript After a Page Load.