onload Function Chaining


ATTENTION: THIS PAGE IS Valid HTML 5 AND IS BEST VIEWED WITH HTML 5 - Please upgrade your browser or download one of the HTML 5 compatible browsers such as Mozilla Firefox, Chrome, Opera or IE 9 (March 14, 2011 or later). For more information see HTML 5 browsers.

If you find this helpful, please click the Google +1 Button to the left, if it is white, to make it turn blue or red. Thank you! (It also helps find this page again more easily.)

PDF mobile

onload Function Chaining

onload Function Chaining using addEventListener

If it does not matter when during the onload event the JavaScript code is executed, simply add an event listener using addEventListener, passing the event object as a parameter:

function init(ev) {
   if (! ev) ev = window.event;
   ... any JavaScript code here runs when the onload event has been triggered ...
window.addEventListener("load", init);

Running JavaScript code before other onload functions

To run JavaScript code during the onload event at specific times relative to other code in the same event, simply replace the window.onload function with a new function that runs the previous onload function at the desired time.

window.onload = function(prevOnloadFunction) {
   return function(ev) {
      if (! ev) ev = window.event;
      ... any JavaScript code here runs before other onload code ...
      if (typeof prevOnloadFunction == "function") prevOnloadFunction();
      else alert("prevOnloadFunction should be a function, not " + typeof prevOnloadFunction);
      ... any JavaScript code here runs after other onload code ...

The previous window.onload function is passed as a parameter to a function that builds the new function (via (window.onload) near the end) so that it is resolved when the new function is being defined. However, since the inner function does not include a parameter list, its code, including the call to the previousOnloadFunction() will not be executed until the onload event has been triggered.

Valid HTML 5