javascript - jQuery best practices in case of $('document').ready -
i researching on jquery best practices , found this article by greg franko
normally, do:
$("document").ready(function() { // dom ready! // rest of code goes here });
but article recommends use:
// iife - invoked function expression (function($, window, document) { // $ locally scoped // listen jquery ready event on document $(function() { // dom ready! }); // rest of code goes here! }(window.jquery, window, document)); // global jquery object passed parameter
i can see comments there, couldn't figure out saying.
so, better approach , why?
i know both methods work, how second 1 become better?
immediately invoked function expressions (iifes)
iifes ideal solution locally scoping global variables/properties , protecting javascript codebase outside interference (e.g. third-party libraries). if writing jquery code run in many different environments (e.g. jquery plugins), important use iife locally scope jquery because can’t assume using $ alias jquery. here how it:
// iife - invoked function expression (function($, window, document) { // $ locally scoped // rest of code goes here! }(window.jquery, window, document)); // global jquery object passed parameter
if don’t having scroll bottom of source file see global variables/properties passing iife, can this:
// iife - invoked function expression (function(yourcode) { // global jquery object passed parameter yourcode(window.jquery, window, document); }(function($, window, document) { // rest of code goes here! } ));
to read more iifes, can read blog post titled, i love iife.
jquery ready event
many developers wrap of code inside of jquery ready event this:
$("document").ready(function() { // dom ready! // rest of code goes here! });
or shorter version this:
$(function() { // dom ready! // rest of code goes here! });
if doing either of above patterns, should consider moving pieces of application (e.g. methods), don’t depend on dom, outside of ready event handler. this:
// iife - invoked function expression (function(yourcode) { // global jquery object passed parameter yourcode(window.jquery, window, document); }(function($, window, document) { // $ locally scoped $(function() { // dom ready! }); // rest of code goes here! } ));
this pattern makes easier separate logic (from code design perspective) since not has wrapped inside of single event handler callback function. improve application’s page load performance, since not needs initialized right away. great example of lazy binding dom event handlers not need bound when dom ready.
adapted jquery best practices blog post: http://gregfranko.com/blog/jquery-best-practices/