Check if jQuery.js is loaded

This article discusses how to check if jquery.js file is loaded. Also, presents a way to force load jQuery file before running any dependant JavaScript code.

In order to determine whether jquery.js file is loaded or not, we need to check for existence of jQuery object. Because, when jquery.js file is loaded, it creates a new global jQuery variable. Checking if some class, method, variable or property does already exist is the very basics of any programming language. In our case, the programming environment is JavaScript and the object we are checking for is jQuery() (or $()).

This method is not limited to jQuery only, you can check existence of any other variable or function in your javascript.

Anyway, as we said earlier, jQuery() or $() functions will only be defined if they are already loaded into the current document. So to test if jQuery is loaded or not we can use 2 methods.

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.

You can also check if particular jQuery plugin is loaded or not.