How To Run Jquery On Page Load

When working with jQuery, it’s essential to ensure that the code runs only after the page has finished loading. This can be achieved by using the $(document).ready() method or the shorthand syntax $(function()). In this blog post, we’ll discuss how to run jQuery on page load using these two methods.

Method 1: Using $(document).ready()

The $(document).ready() method is used to execute a function once the Document Object Model (DOM) is ready for manipulation. This ensures that all the elements are loaded before the jQuery code runs.

To run jQuery code on page load using the $(document).ready() method, follow these steps:

  1. Make sure you’ve included the jQuery library in your HTML file. To include the library using a Content Delivery Network (CDN), add the following line of code within the head tag of your HTML file:

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
          
  2. Add your jQuery code within a script tag, making sure to wrap it inside the $(document).ready() method:

    <script>
    $(document).ready(function() {
      // Your jQuery code goes here
    });
    </script>
          

Method 2: Using $(function()) Shorthand Syntax

You can also run jQuery on page load using the shorthand syntax $(function()), which is an alias for $(document).ready(). This method is more concise and easier to read.

To use the shorthand syntax, follow these steps:

  1. Ensure that the jQuery library is included in your HTML file, as discussed in Method 1.
  2. Add your jQuery code within a script tag, making sure to wrap it inside the $(function()) shorthand:

    <script>
    $(function() {
      // Your jQuery code goes here
    });
    </script>
          

Conclusion

Running jQuery on page load is essential to ensuring that your code executes correctly and doesn’t cause any unexpected issues. By using either the $(document).ready() method or the $(function()) shorthand syntax, you can guarantee that your jQuery code runs only after the DOM is fully loaded.