palAlaa palAlaa - 3 years ago 204
Javascript Question

How do I call a JavaScript function on page load?

Traditionally, to call a JavaScript function once the page has loaded, you'd add an

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
attribute since I'm using JSP fragments, which have no
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download