Skip to content Skip to sidebar Skip to footer

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 su

Solution 1:

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.

Solution 2:

Jquery has $(document).ready()

The ideal point at which to run most scripts is when the document is ready, and not necessarily when it is "loaded".

See here

Solution 3:

I use neither. Instead, I depend on YUI's onDomReady() (or onContentReady()/onAvailable()), because it handles the timing of initialization for me.

(Other JS libraries have similar methods for executing only once the page is fully loaded, as this is a common JS problem.)

Solution 4:

That is not conform to any (X)HTML spec and I would be advised against that. It would put your site in to a quirks mode of the browser.

Solution 5:

The correct way around the issue would be to use the DOMContentLoaded event, which isn't supported in all browsers. Hacks (eg polling doScroll() or using onreadystatechange) exist, so libraries are able to provide this functionality across browsers.

But there are still problems with DOMContentLoaded and chunked transfers which haven't been addressed by popular JavaScript frameworks.

Here's my take on the issue.

Post a Comment for "Initializing Js Components At The End Of Html Or On "onload"?"