How to properly use JavaScript onload function.

JavaScript is most widely used programming language on the web with lots of plugins or libraries available for usage.

The onload function which is fired based on the event raised once the complete document along with the external resources like images,script files,css files, etc. are loaded.

Let's see and example code.

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<script>
	window.onload = function(){
	     console.log("Onload fired 1");
    }
    window.onload = function(){
	     console.log("Onload fired 2");
    }

    window.onload = function(){
	     console.log("Onload fired 3");
    }

	</script>
</head>
<body>
	<h1>Welcome to onload function chaining</h1>
</body>
</html>

 

Once you run the above code and open the browser console you will only see Onload fired 3, this is how onload function will behave if you have multiple function attached to onload poperty of window object, only the last associated function will be executed.

This would result in unexpected behaviour in case of external plugin or libraries depedencies, lets see how can we implement the onload chaining to avoid any as such issues.

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<title>Document</title>
		<!-- <script src="main.js"></script> -->
		<script>
			window.onload = function(){
				alert("Onload fired 1");
			} // might be used in plugin

			customOnload(function(){
				console.log("Onload fired 2");
			}) 
			customOnload(function(){
				console.log("Onload fired 3");
			})
           // custom defined function which expects callback as parameter
			function customOnload(fn){
				var prev = window.onload; // already defined onload reference assigned to prev
				window.onload = function(){
				if(prev){
					prev(); // check if onload already registered then execute 
				}
				fn(); // execute the function passed as argument
				}
			}
		</script>
	</head>
	<body>
		<h1>Welcome to JavaScript onload function</h1>
	</body>
</html>