Built From Developers For Developers
» Kuikie.com » Snippets » JavaScript » Other » JavaScript. Execute JavaScript When Web Page Has Finished Loading

JavaScript. Execute JavaScript When Web Page Has Finished Loading

How many times you needed to execute a JavaScript after the page has loaded? And most of the time developers include third party libraries, just because they have this functionality implemented. But external libraries add extra overhead and cause your page to load really slow, which you really don't need. For instance, adding the great JQuery library will add at least extra 40kb (if compressed and gzipped) or about 240 (if normal code). Compare it with a web page, which is usually about 16-20kb (without images). Well, well, that is two to hundred times the size of the whole page. Not very wise, if I need it just for one small feature.

So here is a pure JavaScript implementation of how to call a function or functions after the web page has been loaded. This snippet uses the web page onload event, which is executed after the web page has finished loading. The snippet will keep any other functionality already attached to the onload event, if any. Additionally, it allows to attach as many functions to it as you want.

var on_load = window.onload+";";
on_load += "my_function_1();"; // Add custom function
on_load += "my_function_2();"; // Add second custom function
on_load += "my_function_3();"; // Add third custom function
window.onload = function() { eval(on_load); }


var on_load = window.onload+";";
on_load += "alert('Hello, I was called after webpage finished loading ;)');";
window.onload = function() { eval(on_load); }
©2012 Sinevia Ltd Terms of Use         Privacy Policy Valid XHTML 1.0 Transitional