Home >Web Front-end >JS Tutorial >How Can I Execute a JavaScript Function on Page Load Without Using the `` Tag?

How Can I Execute a JavaScript Function on Page Load Without Using the `` Tag?

Susan Sarandon
Susan SarandonOriginal
2024-11-15 08:14:02265browse

How Can I Execute a JavaScript Function on Page Load Without Using the `` Tag?

Executing Functions on Page Load Without Body Tag Initialization

The question presents a scenario where a user seeks to execute a function when a page loads, avoiding the use of the tag for initialization. While the attempt to use window.onload = codeAddress; was unsuccessful, this article will provide a solution to this challenge.

The provided code demonstrates the proper usage of the window.onload event listener. When the page is fully loaded and rendered, the window.onload event is triggered, allowing the execution of the specified function. By assigning the codeAddress function to the window.onload property, the function will automatically execute when the page loads.

This is exemplified in the provided code snippet:

function codeAddress() {
  alert('ok');
}

window.onload = codeAddress;

When the page loads, the codeAddress function will be executed, displaying an alert with the message "ok." This illustrates the successful execution of a function upon page load without the need for tag initialization.

The above is the detailed content of How Can I Execute a JavaScript Function on Page Load Without Using the `` Tag?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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