Tuesday, January 13, 2015

JQuery Best Practices - Document ready

Most projects starts like this

$("document").ready(function() {
    // The DOM is ready!
    // The rest of the code goes here
  });

This is fine if

If you know the environments where your code will run
If you do not care about page load performance
If you don't care about best practices

This is better

// IIFE - Immediately Invoked Function Expression

  (function($, window, document) {

    // The $ is now locally scoped

   // Listen for the jQuery ready event on the document
   $(function() {

     // The DOM is ready!

   });

   // The rest of the code goes here!

  }(window.jQuery, window, document));

  // The global jQuery object is passed as a parameter

---------------------------------------------------------------------------------------------------------

No comments:

Post a Comment