Thursday, September 3, 2015

jQuery Howto: Check if jQuery.js is loaded

Method 1:
if (window.jQuery) {  
    // jQuery is loaded  
} else {
    // jQuery is not loaded
}
Method 2:
if (typeof jQuery == 'undefined') {  
    // jQuery is not loaded
} else {
    // jQuery is loaded
}
If jquery.js file is not loaded, we can force load it like so:
if (!window.jQuery) {
  var jq = document.createElement('script'); jq.type = 'text/javascript';
  // Path to jquery.js file, eg. Google hosted version
  jq.src = '/path-to-your/jquery.min.js';
  document.getElementsByTagName('head')[0].appendChild(jq);
}
NOTE:
Here we are checking for jQuery function being defined or not. This is a safe way to check for jQuery library being loaded. In case you are not using any other javascript libraries like prototype.js or mootools.js, then you can also check for $ instead of jQuery.

No comments :