Check if jQuery has been loaded.

This is a short guide on how to check if the jQuery library has been loaded successfully. This may prove to be useful if you are building a JavaScript library or a plugin that relies on jQuery.

Take a look at the following example:

In the JavaScript snippet above, we placed our check inside the window.onload event. This is because we want to make sure that all resources have been downloaded before we check to see if jQuery has been included.

If window.jQuery equates to TRUE, then we assume that the jQuery library has been loaded. If it equates to FALSE, then we assume that it has not been loaded.

If you fail to wrap the check inside the window.onload event, then window.jQuery will probably return FALSE even when jQuery is available. This is because you haven’t given the browser time to download the library and initialize it.

Note that an alternative approach is to use JavaScript’s typeof operator:

If jQuery has not been loaded properly, then the typeof operator will return the string “undefined”. However, if the library has been loaded properly, then the typeof operator will return the string “function”.

Why do I need to check if jQuery has been loaded?

If you are building a portable library that relies on jQuery, then you might want to check for its existence before you attempt to use it. Otherwise, your code will spit out the following error: Uncaught ReferenceError: $ is not defined

Hopefully, you found this guide useful!

Facebook Comments