window.onload and body.onload differences

D

David Otton

Hi, I'm seeing a difference in behaviour between

window.onload = f();

and

<body onload="f();">

Specifically, window.onload appears to fire before all the elements of
the page have been rendered. As the difference is consistent across
IE/Moz/Opera, I'm assuming it's deliberate - can anyone point me
towards where this behaviour of window.onload is defined in the
documentation? TIA.

Example code follows:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Test Page</title>

<script type="text/javascript">
function countTags(){
var allTags = document.getElementsByTagName("*");
var str = "# of tags: " + allTags.length + "\n";
alert (str);
}

window.onload = countTags();
</script>
</head>
<body onload="countTags();">
<p>This is some dummy text</p>
<p>The quick brown fox jumps over the lazy dog</p>
<p>One Two Three Four Five</p>

<p><button onclick="countTags();">Count tags</button></p>
</body>
</html>
 
C

Cenekemoi

Bonjour à David Otton said:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Test Page</title>

<script type="text/javascript">
function countTags(){
var allTags = document.getElementsByTagName("*");
var str = "# of tags: " + allTags.length + "\n";
alert (str);
}

window.onload = countTags();

Be carefull, here "countTags();" is executed (result : 4).
You must write :

window.onload = countTags;
</script>
</head>
<body onload="countTags();">

But now, you have a new value for window.onload !...
 
M

Martin Honnen

David said:
Hi, I'm seeing a difference in behaviour between

window.onload = f();

and

<body onload="f();">

Well there is a difference between HTML markup with embedded JavaScript
code and pure JavaScript, if you want to use script to assign the onload
handler then use
window.onload = f;
that is assign a function and not the result of a function call (f()).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top