views:

82

answers:

3

I want to execute a script after the whole page has loaded, when it's complete.

The current way is:

window.onload=document.getElementById('loaded').value=1;

Which is not good, as some images are still in load, and the page has not completed loading truly. What I am doing wrong?

Certainly doesn't work for me in Chrome and Firefox. The thing is I launch a code after, that returns status 204, and this blocks future loads. But it seams this 204 status is returned way before the page has finished loading. So I need to execute my code after the page has truly loaded.

EDIT

setup a page, that does framebreaking

<iframe id="myframe" height=1 width=1></iframe> 
<script type="text/javascript"> 
window.onload=document.getElementById('myframe').src='http://link to a frame braker page';
</script>

when you put the above code to a page, it loads the iframe before the page is fully loaded. Simply put an alert in the iframe page, and try out on a slower server where your parent page contains large images etc..

+4  A: 

The window.onload event should wait for images to load before it is fired:

The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images and sub-frames have finished loading.

Source: Mozilla Dev Center: window.onload

You may want to check out the following Stack Overflow post for further reading:


UPDATE:

The reason why your implementation is not working has identified by bobince in another answer. The solution is to use:

window.onload = function() {
    document.getElementById('loaded').value = '1';
};
Daniel Vassallo
Well certainly doesn't work for me in Chrome and Firefox. The thing is I launch a code after that returns status 204, and this blocks future loads. But it seams this 204 status is returned way before the page has finished loading. So I need to execute my code after the page has truly loaded.
Pentium10
@Pentium10: That's interesting. Do you think you can post a very short code example that reproduces this problem?
Daniel Vassallo
@Daniel see my Edit.
Pentium10
A: 

If you can use Jquery, have a look to FrameReady plugin.
Check this SO question. for further information

systempuntoout
I was sure OP was talking about Iframe; messed up with another question probably :).
systempuntoout
+3  A: 

window.onload=document.getElementById('loaded').value=1;

You've forgotten to turn that into a function. What you're saying is:

document.getElementById('loaded').value= 1;
window.onload= 1;

Obviously that's not very effective as a load detector. What you meant was probably:

window.onload= function() {
    document.getElementById('loaded').value= '1';
};
bobince
+1 for the detailed explanation, and for actually solving the OP's problem!
Daniel Vassallo