Friday, May 04, 2007

Script element "defer" attribute

Sometime is required write to a script something similar to below code snippet,
<HTML><HEAD><TITLE>Defer attribute Example</TITLE>
<script>
function HelloWorld(){
alert(document.getElementById('bodyDiv').innerText);
}
</script>
</HEAD>
<BODY>
<div id="bodyDiv">Hello world!!!</div>
<script>HelloWorld();</script>
</BODY>
</HTML>

Above code snippet works fine
You would see an alert on page load. Let us rewrite the above code slightly.
<HTML><HEAD><TITLE>Defer attribute Example</TITLE>
<script>
function HelloWorld(){
alert(document.getElementById('bodyDiv').innerText);
}
</script>
</HEAD>
<BODY>
<script>HelloWorld();</script>
<div id="bodyDiv">Hello world!!!</div>
</BODY>
</HTML>
Check the bold portion of the above code. I am calling a script that would try to access a DIV tag which placed below the javascript. This would mean, as you see, the DIV tag is not yet rendered and javascript refers to that object and you will get an error (Refer the image)

To avoid this, you can let IE know that this scripts need to executed only after the page is loaded. It can be done using "defer" attribute of <script> tag. If you set <script defer='defer' >HelloWorld();</script>, this script block will be executed only after the page load.

Typically, above simple scenario can be handled using onload event of body. But this is for any reason it could not be established, this is the workaround. Firefox does not seems to have such issue though.

0 comments: