Home > Web Front-end > JS Tutorial > How to Call a JavaScript Function on Page Load Without the `onload` Attribute?

How to Call a JavaScript Function on Page Load Without the `onload` Attribute?

Susan Sarandon
Release: 2024-11-24 16:17:22
Original
691 people have browsed it

How to Call a JavaScript Function on Page Load Without the `onload` Attribute?

Calling a JavaScript Function upon Page Load Without onload

Traditionally, the onload attribute on the body element was used to execute a JavaScript function when the page fully loaded. However, some frameworks like JSP fragments don't provide a body element to add the onload attribute. This raises the question: Is there an alternative way to call a JavaScript function upon page load without using jQuery?

The Solution: Anonymous Function onload

Instead of directly assigning the JavaScript function to the onload attribute, you can bind it to an anonymous function. This anonymous function can then be invoked when the page loads.

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

This approach allows you to pass parameters to the intended function, potentially making it more versatile. You can also execute multiple functions within the anonymous function if needed.

Remember, this solution relies on the window.onload event listener to execute the JavaScript code once the page has loaded completely. It's a convenient and flexible alternative to the onload attribute when the body element is unavailable.

The above is the detailed content of How to Call a JavaScript Function on Page Load Without the `onload` Attribute?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template