Skip to content
Fix Code Error

How do I call a JavaScript function on page load?

March 13, 2021 by Code Error
Posted By: Anonymous

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.

Solution

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.

Answered By: Anonymous

Related Articles

  • How can I avoid Java code in JSP files, using JSP 2?
  • What's the difference between including files with JSP…
  • JSP tricks to make templating easier?
  • What is the difference between JSF, Servlet and JSP?
  • How to use Servlets and Ajax?
  • Android Gradle plugin 0.7.0: "duplicate files during…
  • How to install JSTL? The absolute uri:…
  • ViewPager and fragments — what's the right way to store…
  • What is the origin of foo and bar?
  • What is your most productive shortcut with Vim?

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How to turn IDENTITY_INSERT on and off using SQL Server 2008?

Next Post:

Count the number occurrences of a character in a string

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Get code errors & solutions at akashmittal.com
© 2022 Fix Code Error