How do I call a JavaScript function on page load?

palAlaa picture palAlaa · Oct 1, 2010 · Viewed 1.1M times · Source

Traditionally, to call a JavaScript function once the page has loaded, you'd add an onload attribute to the body containing a bit of JavaScript (usually only calling a function)

<body onload="foo()">

When the page has loaded, I want to run some JavaScript code to dynamically populate portions of the page with data from the server. I can't use the onload attribute since I'm using JSP fragments, which have no body element I can add an attribute to.

Is there any other way to call a JavaScript function on load? I'd rather not use jQuery as I'm not very familiar with it.

Answer

Matt Sieker picture Matt Sieker · Oct 1, 2010

If you want the onload method to take parameters, you can do something similar to this:

window.onload = function() {
  yourFunction(param1, param2);
};

This binds onload to an anonymous function, that when invoked, will run your desired function, with whatever parameters you give it. And, of course, you can run more than one function from inside the anonymous function.