Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

Checking if jQuery is loaded vs. ready

4.71/5 (7 votes)
3 Oct 2011CPOL 39.3K  
This tip helps you to check if jQuery will be available to your script.

I am currently developing an ASP.NET User Control. My control has dependency on jQuery, so in order for my control to operate correctly and be robust, I needed to check that jQuery has/will be loaded.


First let's define the two states of jQuery:



  • loaded: jQuery is referenced in the current page by way of <script></script> tags.
  • ready: jQuery is loaded and the DOM is ready for manipulation.

A non-denominational web search led me to several articles that suggested one of the following constructs:


kscript
if(jQuery) alert('jQuery is loaded.');

if(typeof(jQuery) != 'undefined') alert('jQuery is loaded.');

That makes sense; however, these simply don't work — at least not in all browsers. In actual practice, these tell us if jQuery is ready, not loaded.


Instead, I determined that the most reliable means of checking if jQuery is loaded is to check if the $ function is defined:


JavaScript
if(typeof($) == 'function') alert('jQuery is loaded.');

Note: this will yield a false positive in the unlikely event that the $ token has been defined by something other than jQuery as a token.


I like to use this anywhere that the standard jQuery $(document).ready() construct is used:


JavaScript
if(typeof($) != 'function') alert('This component requires jQuery.'); 
else $(function() { alert('The DOM is ready for jQuery manipulation.'); });

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)