Monday, May 23, 2011

run javascript after page load

why should we run javascript after a page loaded?

1. If we run javascript immediately after we place it in the HTML page, it will start loading and halt the rest of the HTML page from being loaded unit the javascript finished its job.
2. If a javascript runs before HTML elements are completely loaded, it might not be able to access some of the elements because those elements are not loaded yet.

How to run javascript after a page loaded?

1. The simplest and easiest way: using window.onload
window.onload = function() {
       //run your javascript
This way is very easy and simple. window.onload will NOT get invoked until a HTML page has finished loading everything.
However, it does have issues. It won't run until everything of a page has been loaded. That means, it will wait until large images, videos, music, if your page contains any of them, have been loaded completely. We just want to run our javascript after the browser is aware of the content, but we don't have to wait until the content is actually loaded onto our screen.

2. To fix the issues with window.onload, we can use a javascript library.
Take one of the most popular javascript library, jQuery, for example. We can simply do:
   //run your javascript

jQuery is a fabulous javascript library that worth your time to learn.  Other javascript libraries also provide similar mechanism. For example, extjs method: Ext.onReady()

3. What if we don't want to use any 3rd party javascript library and just want to use native javascript?
In this situation, I personally would suggest simply using window.onload. To fix its issues with native javascript (and DOM) is tedious. I reckon no one will do that in their projects.  3rd party library like jQuery has beautifully wrap the tedious process for us so we can simply call $(document).ready().

No comments: