I want to call a function after a document loads, but the document may or may not have finished loading yet. If it did load, then I can just call the function. If it did NOT load, then I can attach an event listener. I can't add an eventlistener after onload has already fired since it won't get called. So how can I check if the document has loaded? I tried the code below but it doesn't entirely work. Any ideas?
var body = document.getElementsByTagName('BODY')[0];
// CONDITION DOES NOT WORK
if (body && body.readyState == 'loaded') {
DoStuffFunction();
} else {
// CODE BELOW WORKS
if (window.addEventListener) {
window.addEventListener('load', DoStuffFunction, false);
} else {
window.attachEvent('onload', DoStuffFunction);
}
}
You probably want to use something like jQuery, which makes JS programming easier.
Something like:
Would seem to do what you are after.
I have other solution, my application need to be started when new object of MyApp is created, so it looks like:
it is working on all browsers, that i know.
No need for a library. jQuery used this script for a while, btw.
http://dean.edwards.name/weblog/2006/06/again/
Try this:
If you actually want this code to run at load, not at domready (ie you need the images to be loaded as well), then unfortunately the ready function doesn't do it for you. I generally just do something like this:
Include in document javascript (ie always called before onload fired):
Then your code:
(Or the equivalent in your framework of preference.) I use this code to do precaching of javascript and images for future pages. Since the stuff I'm getting isn't used for this page at all, I don't want it to take precedence over the speedy download of images.
There may be a better way, but I've yet to find it.
The above one with JQuery is the easiest and mostly used way. However you can use pure javascript but try to define this script in the head so that it is read at the beginning. What you are looking for is
window.onload
event.Below is a simple script that I created to run a counter. The counter then stops after 10 iterations