To call a JavaScript function when a web page loads, you can use one of two main approaches:
Using an HTML Attribute:
You can use the onload attribute in the <body> or other HTML elements. When the page finishes loading, the browser will automatically call the specified function. This is a simple method but combines HTML and JavaScript in the same place.
Using JavaScript Event Listeners:
You can attach a load event listener to the window object in your JavaScript code. This ensures the function is executed once the entire page, including all resources like images and stylesheets, has been loaded. This approach is cleaner and keeps your JavaScript separate from the HTML structure.
Both methods ensure that the function is triggered when the page has loaded, allowing you to perform tasks like initializing variables, setting up UI components, or loading dynamic content.