Search code examples
javascriptajaxinitialization

Initializing JS components at the end of HTML or on "onload"?


For a while I had been running JavaScript component initialization by waiting for the "onload" event to fire and executing a main() of sorts. It seemed cleaner and you could be sure the ID state of your DOM was in order. But after some time of putting that through its paces I found that the component's initialization was choked off by any sort of resource hanging during the load (images, css, iframes, flash, etc.).

Now I have moved the initialization invocation to the end of the HTML document itself using inlined <script /> execution and found that it pushes the initialization before other external resources.

Now I wonder if there are some pitfalls that come with doing that instead of waiting for the "onload".

Which method are you using?

EDIT: Thanks. It seems each library has a specialized function for DOMContentLoaded/readyState implementation differences. I use prototype so this is what I needed.


Solution

  • For me, we use jquery, and its document ready state ensures that the DOM is loaded, but is not waiting for resources like you say. You can of course to this without a javascript framework, it does require a function you can create for example: document ready Now, for the most part putting script at the end of the page sure ensure the rest of the page is there, but making sure the DOM is ready is never a bad thing.