How to check if jQuery is loaded and include it programatically if not

Hello,

There are many a times when you want to do this but if you are a plugin or jQuery widget developer then this becomes much more important.

It becomes important because your widget or plugin may not work if jQuery is not present. right?

Ok so lets check it out

To check if jQuery is present or not then you can choose any one of these methods

First method

  1. if(typeof jQuery == 'undefined') {
  2.    // jQuery is not present
  3. } 
  4. else {
  5.   // jQuery is loaded
  6. }

 

Second Method

This is a bit more comprehensive and check if jQuery is not present to jQuery has preoperly loaded yet


  1. if (typeof jQuery == 'undefined' || typeof jQuery != 'function' || jQuery("*") === null) {
  2. // jQuery is not read yet or its still loading. Defer your stuff for some time and check again
  3. } 
  4. else {
  5. // all good
  6. }

Alrigth so now we know how to check if jQuery is loaded or not now we want to include it if its not there at all this is how I do it normally.

Including jQuery programatically

I will just copy the first method here and put the jQuery inclusion code in the first if

  1. if(typeof jQuery == 'undefined') {
  2.    // jQuery is not present, lets include it
  3. var header = document.getElementsByTagName("head");
  4. // you may want to check if head is present or not but for all modern browser it will be
  5.         var jqscript = document.createElement("script");
  6.         jqscript.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js";
  7.         header[0].appendChild(jqscript);
  8. // this can take upto few seconds so you may want to
  9. // defer your code from executing few seconds and possible checking
  10. // with second method if jQuery is now available
  11. } 
  12. else {
  13.   // jQuery is loaded
  14. }

Ok so this is how I would approach this problem. If you think of something that can be done to improve this please share it using site comments.

I hope that this helps you in one way or another.

Cheers

Advertisement

 

 

 

VN:F [1.9.22_1171]
Rating: 0.0/5 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Speak Your Mind

*

CommentLuv badge