How To Make Javascript Run On Page Load

When creating interactive web applications, it is often essential to execute JavaScript code as soon as the page loads. This enables users to immediately interact with the application without having to perform any action. In this blog post, we will discuss different techniques to make JavaScript run on page load.

1. Using the <body> Tag’s onload Attribute

The simplest and most straightforward method is to use the onload attribute of the <body> tag. The value of this attribute should be a JavaScript function that you want to execute when the page loads.

Here’s an example:

    
        ...
        <script>
            function myFunction() {
                alert('Welcome to my website!');
            }
        </script>
    
    

In this example, an alert box is displayed when the page loads, welcoming the user to the website.

2. Using a <script> Tag Inside the <body> Tag

Another method is to place a <script> tag right before the closing </body> tag. This ensures that the script is executed after the HTML has been fully parsed and the DOM is ready.

Here’s an example:

    
        ...
        <script>
            function myFunction() {
                alert('Welcome to my website!');
            }
            myFunction();
        </script>
    
    

This method is very similar to the previous one, but it allows you to keep all your JavaScript code within the <script> tag and does not require using any HTML attributes.

3. Using the DOMContentLoaded Event

With this technique, you can execute JavaScript code as soon as the DOM is ready, even before all images and other resources have been loaded. You can attach an event listener to the window object and listen for the DOMContentLoaded event.

Here’s an example:

    <script>
        function myFunction() {
            alert('Welcome to my website!');
        }

        document.addEventListener('DOMContentLoaded', myFunction);
    </script>
    

This method ensures that your JavaScript code is executed as soon as the DOM is ready, which can potentially improve the perceived loading time of your web application.

Conclusion

In this blog post, we have discussed three different techniques to make JavaScript run on page load. Each technique has its own advantages, and the best one for you depends on your specific use case and requirements. Experiment with these techniques and find the one that suits your needs the best!