Multiple onload handlers using vanilla Javascipt

Attaching a function to windows on load event can be done in multiple ways using plain vanilla Javascript. One option is to use wondow.onload where we can attach only one handler. Other option is to use window.addEventListener('load', functionName) which supports multiple handlers. Here are examples with these approaches.

Using window.onload

window.onload allows only on handler. So we’ll have to wrap the old handler and new handler in a wrapper function.

<div id="log">
</div>
<script type="text/javascript">
function my_attach_handler(f1) {
  var old = window.onload;
  if (old) {
    window.onload = function() { old(); f1();} ;
  } else {
    window.onload = function() { f1();} ;
  }
}
my_attach_handler(handler1);
my_attach_handler(handler2);
function handler1() {
  document.querySelector("#log").innerHTML += "in handler1<br/>"; 
}
function handler2() {
  document.querySelector("#log").innerHTML += "in handler2<br/>"; 
}
</script>
refresh

Using window.addEventListener

Since addEventListener works in most modern browsers including IE9 and above, this approach is also a viable approach now.

<div id="log">
</div>
<script type="text/javascript">
window.addEventListener('load', handler1);
window.addEventListener('load', handler2);
function handler1() {
  document.querySelector("#log").innerHTML += "in handler1<br/>"; 
}
function handler2() {
  document.querySelector("#log").innerHTML += "in handler2<br/>"; 
}
</script>
refresh

In case you need to support IE8, you can use the following code snipper

if (window.addEventListener) {
  // use window.addEventListener
} else if (window.attachEvent) {
  // IE8 etc.
  // use window.attachEvent
}
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments