Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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.

like image 565
palAlaa Avatar asked Oct 01 '10 19:10

palAlaa


People also ask

How do you load a function in JavaScript?

load() . The load() method attaches an event handler to the load event. The load event occurs when a specified element has been loaded. This event works with elements associated with a URL (image, script, frame, iframe), and the window object.

How do I call a JavaScript function call?

The JavaScript call() MethodThe call() method is a predefined JavaScript method. It can be used to invoke (call) a method with an owner object as an argument (parameter). With call() , an object can use a method belonging to another object.

How do you call a JavaScript function in HTML?

The first method is to call the JavaScript function in HTML. For this, you have to create a function then define this function either in the head section or body section of the HTML document. You can either create a link or a button and then an onclick() event is associated with them in order to call this function.


1 Answers

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.

like image 54
Matt Sieker Avatar answered Oct 04 '22 03:10

Matt Sieker