show progressbar while loading pages using jquery ajax in single page website

show progressbar while loading pages using jquery ajax in single page website

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Why Progress Bars in jQuery .load() Fail and How to Fix Them

Building a single-page application (SPA) feel without a framework often involves using jQuery's .load() method to fetch content into a wrapper div. A common requirement for this pattern is displaying a progress bar to indicate loading status, similar to the Gmail spinner. The naive approach relies on manipulating the DOM of the returned HTML string while the data is still in transit.

As seen in the provided code, the developer attempts to update the progress bar width inside the success callback: wrap.load(url, function(){...}). However, this method has a fundamental flaw. When jQuery executes .load(), it fetches the entire HTML response and inserts it into the DOM before the success callback runs. The script tags contained within that HTML are executed synchronously as part of the DOM insertion process.

In this specific scenario, the remote page returns JavaScript that manipulates the progress bar:

<script>$('.progressbar .bar').css('width','30%');</script>
<link href="/assets/css/datepicker.css" rel="stylesheet" />
<script>$('.progressbar .bar').css('width','60%');</script>

While this works in Firefox, Chrome and Internet Explorer fail to render the progress bar correctly. The core issue is that jQuery does not provide real-time access to the XMLHttpRequest object during the .load() operation. Once the data arrives and is injected, the browser executes the scripts immediately. By the time the script runs, the XHR state has already transitioned from "loading" to "complete." Consequently, any logic relying on the active loading state or updating the UI based on partial data receipt cannot function as intended within the success callback of .load().

The Correct Approach: Using $.ajax with progress Events

To achieve a Gmail-like experience where you can update the progress bar in real-time, you must bypass jQuery's high-level convenience methods like .load() for the transport layer and use $.ajax directly. This gives you access to the underlying XHR object, which exposes the progress event.

The strategy involves two distinct steps:

  1. Initiate the Request: Use $.ajax to start the fetch operation and listen for the progress event.
  2. Handle the Response: Process the loaded content once the request completes, ensuring the progress bar is hidden after the final update.

Here is how you can refactor the implementation:

$('.ajaxspl').on('click', function(e) {
    e.preventDefault();

    var url = $(this).data('url'),
        wrap = $('body #wrap');

    // Clean the wrapper before loading new content
    wrap.slideUp().html('');

    // Show the progress bar immediately upon starting the request
    $('.progressbar').fadeIn();
    $('.progressbar .bar').css('width', '5%');

    $.ajax({
        url: url,
        method: 'GET',
        success: function(responseText) {
            // Update the progress bar one last time to indicate completion
            $('.progressbar .bar').css('width', '100%');
            
            // Insert the HTML content into the wrapper
            wrap.html(responseText).slideDown();

            // Hide the progress bar after a short delay or immediately if desired
            setTimeout(function() {
                $('.progressbar').fadeOut();
            }, 300);
        },
        error: function(xhr, status, error) {
            $('.progressbar').fadeOut();
            console.error('Error loading page:', error);
        }
    })
    .progress(function(event, position, total) {
        // Calculate percentage loaded. Note: total is not always available (undefined in early Chrome versions).
        var percent = total && position ? Math.round((position / total) * 100) : 5;
        
        // Ensure the bar doesn't drop below a minimum width
        if (percent < 5) percent = 5;

        $('.progressbar .bar').css('width', percent + '%');
    });
});

Handling Cross-Origin Restrictions

A critical pitfall to consider is the Cross-Origin Resource Sharing (CORS) policy. If your navigation links point to URLs on a different domain than your main application, the browser will block the progress event from firing for security reasons. The onprogress handler will simply not execute when fetching resources from external domains unless the server explicitly sends the appropriate CORS headers.

In cases where you are loading content from the same origin (same protocol, domain, and port), the progress event works reliably across all modern browsers, resolving the incompatibility issues seen with Chrome and IE in the original approach. If cross-origin loading is required, you must ensure the server hosting the remote page includes headers like Access-Control-Allow-Origin: *.

Conclusion on Implementation

By switching from .load() to $.ajax and listening for the progress event, you gain precise control over the loading state. This method allows you to update the UI incrementally, providing a smoother user experience that mimics modern single-page applications while maintaining compatibility with all major browsers.

Our network