Execute Functions After Page Load Using jQuery

I was working on a client project where I needed to make sure certain JavaScript functions only ran after all the page elements were fully loaded. The challenge was that some functions were trying to manipulate DOM elements that weren’t yet available, causing errors and broken functionality.

The solution was to use jQuery to properly execute these functions only after the page had loaded. This simple technique immediately fixed the timing issues and made the site work perfectly.

In this article, I’ll cover several reliable methods to execute functions after page load using jQuery. Whether you’re building a simple website or a complex web application.

Page Load Events in jQuery

Before getting into the solutions, it’s important to understand the different page load events in jQuery:

  1. $(document).ready() – Executes when the DOM is fully loaded
  2. $(window).load() – Executes when the entire page (including images and external resources) is loaded
  3. Modern syntax alternatives – Shorter, more efficient ways to handle these events

Let’s explore each method with practical examples.

Read 51 jQuery Examples with Source Code

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

The most common way to execute code after the DOM is loaded is by using the $(document).ready() method. This ensures your code runs as soon as the DOM is ready for JavaScript manipulation, even before all images and external resources finish loading.

This is the HTML code that gives the basic structure

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>jQuery Date Picker Example</title>

    <!-- jQuery Library -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

    <!-- jQuery UI Library (for datepicker) -->
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>

    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 40px;
        }
        input {
            padding: 8px;
            font-size: 16px;
        }
    </style>
</head>
<body>

    <h2>Select a Date</h2>
    <input type="text" id="datepicker" placeholder="MM/DD/YYYY">

    <!-- Link to your external JS file -->
    <script src="script.js"></script>

</body>
</html>

I executed the above example code and added the screenshot below.

Execute Functions After Page Load Using jQuery
$(document).ready(function() {
    // Your code here
    console.log("DOM is ready!");

    // Example: Initialize a date picker on a form
    $("#datepicker").datepicker({
        dateFormat: "mm/dd/yy",
        changeMonth: true,
        changeYear: true
    });
});

I executed the above example code and added the screenshot below.

Use jQuery to Execute Functions After Page Load

In this example, I’m initializing a date picker component as soon as the DOM is ready. This works well because we don’t need to wait for images to load before making the form interactive.

You can also use the shorter syntax:

$(function() {
    // Your code here
    console.log("DOM is ready - shorter syntax!");

    // Example: Show a welcome message
    $("#welcomeMessage").fadeIn(1000);
});

The shorter syntax is exactly equivalent to the longer version, but makes your code cleaner and more concise.

Check out JavaScript Examples [51 Useful Examples]

Method 2: Use $(window).load()

If you need to execute code after everything on the page is fully loaded (including images, iframes, and other external resources), use the $(window).load() method:

This is the HTML code for the structure.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Image Load Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        #status {
            font-weight: bold;
            margin-top: 20px;
        }
    </style>
</head>
<body>

    <h2>Image Load Checker</h2>
    <img id="myImage" src=images/app_icon.png alt="Sample Image" />
    
    <p id="status">Waiting for image to load...</p>

    <script src="script.js"></script>
</body>
</html>

I executed the above example code and added the screenshot below.

How to Use jQuery to Execute Functions After Page Load
// Code that waits for full page (including image) to load
$(window).on("load", function() {
    $("#status").text("✅ Image and page fully loaded!");
    console.log("Window is fully loaded including images.");
});

I executed the above example code and added the screenshot below.

How to Execute Functions After Page Load Using jQuery

This method is particularly useful when working with:

  • Image galleries
  • Complex layouts that depend on image dimensions
  • Charts or visualizations that need precise dimensions

In modern jQuery (3.0+), the recommended syntax is:

$(window).on("load", function() {
    // Your code here
    console.log("Window fully loaded - modern syntax");

    // Example: Hide the loading spinner
    $("#loadingSpinner").fadeOut(500);
});

Read Check Which Radio Button is Selected Using jQuery

Method 3: Use Shorthand Document Ready

jQuery provides an even shorter syntax for the document-ready event:

$(function() {
    // DOM is ready

    // Example: Initialize tooltips
    $('[data-toggle="tooltip"]').tooltip();
});

I often use this shorthand syntax in my projects because it’s clean and efficient while maintaining readability.

Method 4: Multiple Document Ready Handlers

You can have multiple document-ready handlers in your code, and they’ll execute in the order they appear:

$(function() {
    console.log("First handler");
    // Initialize basic UI elements
    $(".dropdown-toggle").dropdown();
});

$(function() {
    console.log("Second handler");
    // Setup event listeners
    $("#contactForm").on("submit", validateForm);
});

This is useful when organizing code into logical sections or when working with multiple JavaScript files that all need to run code when the DOM is ready.

Check out Handle Dropdown Change Event in jQuery

Method 5: Check if the Document is Already Ready

Sometimes your script might load after the DOM is already ready. In these cases, jQuery handles this automatically, but you can also explicitly check:

if (document.readyState === "complete" || document.readyState === "interactive") {
    // Document is already ready, execute code immediately
    initializeApp();
} else {
    // Wait for document to be ready
    $(document).ready(initializeApp);
}

function initializeApp() {
    console.log("App initialized!");
    // Your initialization code here
}

This pattern is useful for scripts that might be loaded dynamically or late in the page lifecycle.

Read Check if a Checkbox is Checked Using jQuery

Real-world Example: Build a Weather Dashboard

Let’s look at a practical example of using these concepts together. Imagine we’re building a weather dashboard for users across the USA:

// Basic UI setup as soon as DOM is ready
$(function() {
    // Setup UI elements immediately
    $("#locationInput").autocomplete({
        source: usaCities,
        minLength: 2
    });

    // Add event listeners
    $("#searchBtn").on("click", fetchWeatherData);

    // Initialize with default location (New York)
    setupDefaultView();
});

// Load weather map after all page resources are loaded
$(window).on("load", function() {
    // Initialize weather map (heavy operation)
    initializeWeatherMap("map-container", {
        center: [40.7128, -74.0060],  // New York coordinates
        zoom: 5
    });

    // Hide loading overlay with a fade effect
    $("#pageLoader").fadeOut(800);
});

function setupDefaultView() {
    // Set up default dashboard view
    $("#currentLocation").text("New York, NY");
    fetchWeatherData("New York");
}

function fetchWeatherData(location) {
    // Simulated API call to fetch weather data
    console.log("Fetching weather for: " + location);
    // API calls would go here
}

function initializeWeatherMap(containerId, options) {
    console.log("Weather map initialized");
    // Map initialization would go here
}

// Sample data
const usaCities = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix", "Philadelphia", "San Antonio", "San Diego"];

In this example, I’m using the document ready handler to set up UI elements and event listeners immediately, while deferring the heavier map initialization until the window load event.

Best Practices for Using jQuery Load Events

After working with these methods for years, I’ve developed these best practices:

  1. Use document.ready for most initialization code – This covers 90% of use cases and doesn’t make users wait unnecessarily.
  2. Reserve window.load for image-dependent functionality – Only use this when you truly need all resources to be loaded.
  3. Keep your handlers focused and minimal – Large blocks of code in ready handlers can slow down page responsiveness.
  4. Consider performance implications – Document-ready handlers block rendering, so keep them lightweight.
  5. Use modern syntax – The .on("load", function(){}) syntax is preferred in newer jQuery versions.

Read Call a JavaScript Function When a Checkbox is Checked or Unchecked

Troubleshoot Common Issues

If you’re having issues with your load event handlers, check for these common problems:

  1. jQuery not loaded – Make sure jQuery is loaded before your code runs.
  2. Conflicting with other libraries – Use jQuery.noConflict() if needed.
  3. Timing issues – Ensure your handlers are defined before the events occur.
  4. Code errors preventing execution – Check the console for JavaScript errors.

jQuery’s load event handlers are powerful tools for ensuring your JavaScript code runs at exactly the right moment. By understanding when to use each method, you can create web applications that initialize smoothly and function reliably.

The methods that I explained in this article are: using $(document).ready(), using $(window).load(), using shorthand document ready, multiple document ready handlers, and checking if the document is already ready.

Other articles you may also like:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.