Friday, October 5, 2012

Why using onload() in a body tag is a bad idea ?

                                         Let's go back to our innocent  years :

Keep Javascript unobtrusive :

To keep our Javascript unobtrusive we can keep it in a single file to avoid messing up the markup of the page. To execute the functions in our .js file, we need to call them when the page has loaded. This can be achieved in various ways and each has it's advantages and disadvantages  .

I am feeling a little nostalgic :

Back when we had just started messing around with Javascript  we used to add the onload to the body element, like this :

body onload = "callMyFunction();"

But, this is bad , real bad .

Why ? --> If we call the script(s) in the body element, we really achieve nothing, since we are still mixing markup and event calls.What we need to do is to separate the call out into a .js file.

I am all grown up :

Now the better way is to attach  the call to the onload event of the window object.

When we only use one function, we don't use the parenthesis at the end of the function name, as that would send back the result of the function rather than trigger the function.

If we have more than one function, we have to use an anonymous function that calls the others, this time with parenthesis.

This is achieved as :


window.onload=callMyFunction; //Notice that there is no ()

or

window.onload=function(){  //Here you need to give () as you are calling an anonymous       // function
 callMyFunction1();
 callMyFunction2();
 callMyFunction3();
}

This will prevent us from messing up our mark up of the page rendered .



1 comment:

  1. try window.onload on Safari...

    You're in for a surprise :)

    ReplyDelete