A typical question asked in "History of JavaScript" classes where the teacher mistakenly believes they are teaching programming.


You have a number of separate scripts that need to be added to your web site. Some of these scripts need code to be run once the page finishes loading. Given that there may be none, one or more of these scripts needing code to run onload in each page, write a function that will automatically add the required functions into the function that runs when the page finishes loading.

This is a question that assumes that there are going to be multiple scripts needing to share the same event handler whereas modern JavaScript almost never needs to handle that event and when it does can solve the problem easily using event listeners.

Historical Answer:

function addOnLoad(newFunction){
var oldOnLoad = window.onload;
if(typeof oldOnLoad == "function"){
window.onload = function(){
} else {
window.onload = newFunction;

Here we have a function that is dynamically creating a window.onload event handler if one doesn't exist and which dynamically updates the function that gets run onload for each addOnload call that is made. The addOnload calls can be included with the separate scripts that need them and will run when that particular script is added to the page so as to update the onload event handler to include the calls for all the scripts added into the page without calling code from any scripts not added.

There are two issues with the actual question in this situation. Firstly, the load event for the window almost never needs to be called. By placing the JavaScript at the bottom of the page just before the closing body tag the script will run after all the HTML has loaded. Most scripts simply need the HTML to have loaded before they can run and do not really need to wait for all the other files the page references to load as well.

The second issue with this question is that the problem it is asking you to solve only exists with old style event handlers. It is not an issue at all using modern event listeners.

JavaScript Answer:

window.addEventListener('load', initOne, false );
window.addEventListener('load', inittwo, false );
window.addEventListener('load', initthree, false );

Assuming that you do actually have multiple functions that need to be run when the load event for the page triggers you can add each one independently with a separate event listener call without them overwriting each other the way that they would if you used event handlers without all the extra code. Most of the time though you'd just run the three functions immediately as a part of the script attached to the bottom of the page.


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow