We know We can do:
We can use the body tag:
...or We can even try at the bottom of the page after everything but the end body or html tag like:
What is a cross-browser(old/new)-compliant method of issuing one or more functions in a manner like jQuery's $.ready()?
The simplest thing to do in the absence of a framework that does all the cross-browser compatibility for we is to just put a call to our code at the end of the body. This is faster to execute than an onload handler because this waits only for the DOM to be ready, not for all images to load. And, this works in every browser.
If we really don't want to do it this way and we need cross browser compatibility and we don't want to wait for window.onload, then we probably should go look at how a framework like jQuery implements it's $(document).ready() method. It's fairly involved depending upon the capabilities of the browser.
To give we a little idea what jQuery does (which will work wherever the script tag is placed).
If supported, it tries the standard:
with a fallback to:
or for older versions of IE, it uses:
with a fallback to:
And, there are some work-arounds in the IE code path that We don't quite follow, but it looks like it has something to do with frames.
The latest version of the code is shared publicly on GitHub at
This has been tested in:
The trick here, as explained by the original author , is that we are checking the document.readyState property. If it contains the string in (as in uninitialized and loading, the first two DOM ready states out of 5) we set a timeout and check again. Otherwise, we execute the passed function.
Above is the equivalent of Jquery .ready:
Which ALSO could be written SHORTHAND like this, which jQuery will run after the ready even occurs.
NOT TO BE CONFUSED with BELOW (which is not meant to be DOM ready)
DO NOT use an IFFWE like this that is self executing : example:
This IFFWE will NOT wait for our DOM to load. ( I'm even talking about latest version of Chrome browser!
example inline usage:
Our method (placing script before the closing body tag)
is a reliable way to support old and new browsers.