JS: Why have “(document).ready” inside “(document).ready”?

So, I ran into a peculiar construction just now:

$(document).ready(function() {var i = 0;
$(document).ready(function() {
… your code here …
});
});

Of course, experienced developers sometimes use the shorthand $() for $( document ).ready().

I found a nice discussion of one use case here, but it doesn’t really fit the code above. It’s more like this:

$(document).ready(function() {var i = 0;
…some code here that we want to have priority

$(document).ready(function() {
… your low-priority code here …
});

…some code here that we want to have priority
});

So, the clue seems to be that all the functionality is not double-wrapped. There is the creation of the variable i in the outer scope.

Later… Okay, I’ve decided that the code at the top of this page is pointless because there is no secondary html creation for which the secondary JS functionality would need to wait.

But imagine you had an AJAX call that brought in a new raft of html. Then, in turn, you want for your JS to listen to inputs or somehow modify that added html. It sure would be a good idea to make the script wait until the new html is fully loaded, right?

Well, that ‘s exactly what an inner/secondary window.ready call would do for you: make the Javascript wait while all the html loads. Nice.

[Seems to be contested by this well-liked page, but see this comment and the simple test that should easily resolve the dispute.]

Leave a Reply