Wednesday, November 13, 2013

jQuery library loaded or not validation

Learning AngularJS; Guide for beginners:

If you are using jQuery on your page, then you should first validate that whether library file loaded or not because if your jQuery file is not loaded when you trying to run your jQuery code it will start throwing exception. So I would suggest you handle this situation instead of breaking page flow show your user a friendly message that required files are not loaded.

The reasons might be possible when your jQuery file not get loaded:

  1. Path referencing a jQuery file is not correct.
  2.  jQuery file name is renamed
  3.  If you are using CDN, and user has blocked your CDN path.
  4. Referenced CDN  server is down.
To handle this you should need to put a check before executing jQuery code, that validate whether file is loaded or not. If it is not available then you can prompt user the instructions to check or follow.

There are different ways to validate this:

if (window.jQuery) {  
    // jQuery library loaded  
} else {
    // jQuery library is not loaded
}

another way to check:

if (typeof window.jQuery == 'undefined') {  
    // jQuery library is not loaded
} else {
    // jQuery library is loaded
}


If  jquery.js library is not loaded, you can force to try again to load the file (but make sure you only using JavaScript as jQuery is not available at the time):

if (!window.jQuery || typeof window.jQuery == 'undefined') {
  // create script Element and append in head of HTML
  var jqElement = document.createElement('script'); 
  jqElement.type = 'text/javascript';
  // Path to jquery.js file, eg. Google hosted version
  jqElement.src = '/path-to-your/jquery.min.js'; //or reference an alternate CDN link
  document.getElementsByTagName('head')[0].appendChild(jqElement);
}

You might have noticed that we are only validating jQuery function being defined or not instead of $.

Reason is that this is a safe way to validate for jQuery file being loaded or not because you might using others libraries i.e, mootools.js then $ will conflict with these libraries. But if you are sure that you are not using others libraries that may conflict with jQuery then you can safely validate it by $ like:



if (typeof window.$ == 'undefined'){ 
  //file not loaded 
}

Similarly if you need to validate any jQuery plugin loaded or not you can easily validate it, as jQuery plugins are namespaces on the jQuery scope. Check that namespace for particular plugin exist or not:
if(window.jQuery().pluginName) {
     //run plugin dependent code
 }

If you want to add anything on this post please post your comments.

1 comment:

  1. You should stick with window.jQuery and window.$, even for typeof checks. Otherwise, if undefined, you run into error and won nothing :)
    Cheers, jovi

    ReplyDelete

Life insurance policy, bank loans, software, microsoft, facebook,mortgage,policy,