PDA

View Full Version : window.onload vrs <body onload="">



Cyclone
03-16-2009, 10:07 AM
Hi,

I have a div element that contains some text. I need to know the height of this text before the page is displayed and I'm trying to find the quickest method possible.

1. Is body onload faster then using window.onload?
2. Do these events get executed before any of the page is displayed?
3. Can you use body onload in a external javascript file instead of in the <body> tag?

The reason I'm wondering is I don't want the elements to 'flicker' on the page after I set style properties using javascript. The page should display properly immediately without any changes.

Thanks

molendijk
03-16-2009, 03:14 PM
1. Is body onload faster then using window.onload?

I don't know, although I would guess that 'body onload' would be faster.


2. Do these events get executed before any of the page is displayed?

No, since the page has to load first.


3. Can you use body onload in a external javascript file instead of in the <body> tag?

Yes, since

<script type="text/javascript">
function bla(){
...do-something...
]
</script>
...
<body onload="bla()">

can be replaced with:


<script type="text/javascript">
function bla(){
...do-something...
]
window.onload=bla;
</script>

which, in turn, can be put in an external js-file.
===
Arie.

magicyte
03-17-2009, 01:51 AM
1. Is body onload faster then using window.onload?

They have just about the same speed.


2. Do these events get executed before any of the page is displayed?

As molendijk said, no. They execute after the loading of the page and its elements. For example, if you have a large image that is taking a while to load, it will execute after that image loads.


3. Can you use body onload in a external javascript file instead of in the <body> tag?

As molendijk said, yes. Simply take the window.onload = function() { /* code here */ }; and place it into the external file. Note that you can not use window.onload and <body onload=""> simultaneously.


I have a div element that contains some text. I need to know the height of this text before the page is displayed and I'm trying to find the quickest method possible.

It's actually impossible, considering that the page must load before you can do anything with the elements on the page. See, you can execute javascript before the page even loads, though it is not allowed to retrieve elements. The elements have not loaded then, thus you cannot access them because they do not exist. In turn, it will have to flicker if you want your javascript to occur. Questions?