I have asked a similar question before but I never made my point exactly clear, or at least I think it’s such a relevant question that it’s worth to bring it up and see if anyon
One advantage would be, that you are able to place the code anywhere in the page. In our case, we use a templating system in our CMS that stitches the page together from around 10 - 30 templates for the different parts (depending on complexity).
Since you want the templates to work on any page they are used, you need to include the necessary Javascript in it. For those cases, the ready()
function is a real life saver.
If you've written a JS file that other people are including in their pages it is safer to use document.ready within that file (assuming it needs to do some processing automatically after the DOM is ready) because you can't be sure whether the file will be included in the head or at the end of the body.
When it comes to pages that you have complete control over then obviously you don't have that worry, so I don't see that it is any more "safe" to use document.ready rather than calling your init()
from the end of the body. Using document.ready (or onload) and putting script at the end of the body are the two most common ways to do it, and they're common because they both work well.
You mentioned document.write()
as a possible exception, but you don't want to be calling that from document.ready or at the end of the body because either way the whole page has already been parsed.
Because it makes domReady and window.load slower.
It's easy to optimize to the metric, rather than the actual user experience. So the "real user optimization" graphs go down, even though interactivity is delayed.
To the point first:
No, there is no disadvantage in calling you init
before closing the <body>
. It will as you have noticed perform better that relying on $.ready()
and will also work with all the browsers flawlessly (even on IE).
Now, there are however reasons to use $.ready()
, which in your case they do not probably apply:
$.ready()
makes it easy for developers to do stuff in the right order. In particular, the critical thing is to not reference DOM elements that have not been loaded. While this is simple enough, lots of developers still find it confusing. $.ready()
is a no-brainer, albeit a slow one.init()
, it is not necessarily easy/convenient to manually do that at the end of your body. It requires discipline and knowledge of what these scripts do. In particular you will often see $.ready()
in libraries dependent on jQuery, since it makes things work no matter what way developers will use to load the libs.<body/>
method is not guaranteed.