[Coding] JavaScript – A Different Way to Use document.ready()
Posted by Khatharsis on November 24, 2013
While doing a search on best practices for storing jQuery objects into variables, I got a little sidetracked into more general best practices articles. One of the tips by Greg Franko had me scratching my head. The syntax wasn’t immediately clear and the comments, both in the code and outside of it, wasn’t particularly helpful, either.
The use of immediately-invoked function expressions (IIFE; see Ben Alman’s article) is a practice I am familiar with after developing a couple of apps using the dynamic namespacing pattern. However, Franko’s use of the pattern was not clear to me and left me a little bit confused.
To give the appropriate background, the practice in question was invoking jQuery’s $(document.ready(function() {}) or $(function() {}) function. His first solution, or the “better practice,” was clear to me as it is a straightforward implementation of IIFE:
(function($, window, document) {
$(function() {
// The DOM is ready!
});
}(window.jQuery, window, document));
An IIFE is invoked and passed three global parameters (window.jQuery, window, document). The code inside the document.ready() function ($(function() {})) can access the global objects through the arguments passed in ($, window, document).
Fairly simple right? Well, take a look at the “best practice” version:
(function(yourcode) {
yourcode(window.jQuery, window, document);
}(function($, window, document) {
$(function() {
// The DOM is ready!
}));
According to another post by Franko, the reason for this format is to enhance readability. That is, instead of having to scroll down to the end of the document to see the parameters that are being passed to the IIFE, they are near the top of the expression of the IIFE.
Of course, it is a matter of personal opinion as to whether it is more readable or not. Personally, the yourcode() expression is a little confusing and at first glance seems almost recursive. Nonetheless, wrapping the document.ready() in an IIFE is a good idea. Also, since I generally put an init() function in my document.ready() code, it is already compact and I don’t see myself needing to use the “best practice” in that case.
One last note, I have found learning various syntax-y things about JavaScript is a method of gaining a deeper understanding of how JS works. It may appear that things are straightforward, but some creative developer leverages some quirk of JS, resulting in some foreign-looking syntax, yet it still works and sometimes even becomes a good practice (like dynamic namespacing).