Using Multiple JavaScript Onload Functions

 Sometimes, many functions are called after pageload (html page). It is not good if we write code directly in html, not in function, exspecially when we use back button  in IE browser.

<body>

….

<script> callSomeThingDirectly(); </script>

….

</body>

The callSomeThingDirectly() function runs before page onload, so it gets old value of the browser.

It’s better and works well if we call the functions in pageload, like this:

function func1() {
  alert(“This is the first.”);
}
function func2() {
  alert(“This is the second.”);
}

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != ‘function’) {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}
addLoadEvent(func1);
addLoadEvent(func2);
addLoadEvent(function() {
    document.body.style.backgroundColor = ‘#EFDF95’;
})

Source:  http://www.htmlgoodies.com/beyond/javascript/article.php/3724571

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: