Pace.js Tutorials
Pace.js Tutorials

Unlocking a Smoother Web Experience: Add a Slick Loading Bar with Pace JS (No Coding Required!)16 min read

  Reading time 22 minutes

We’ve all been there. Clicking a link, and then… silence. A blank screen, or maybe just a spinning favicon, leaving you wondering if the page is loading at all. In today’s fast-paced digital world, even a few seconds of uncertainty can feel like an eternity to your users. This is where a simple yet effective tool can make a world of difference: a page load progress bar.

Instead of leaving your users guessing, a progress bar provides visual feedback, showing them that something is happening and approximately how much longer they might need to wait. It doesn’t necessarily make your website faster, but it feels faster and significantly improves the user experience (UX).

But wait, doesn’t adding a progress bar require complex JavaScript coding, tracking assets, and managing loading states? Traditionally, yes. But what if there was a super simple, almost magical library that did it all automatically?

Enter Pace.js.

What is Pace.js? Your Automatic Page Load Progress Bar Buddy

At its core, Pace.js is a lightweight JavaScript library that creates an automatic progress bar for your website. And when we say automatic, we really mean it! For many websites, all you need to do is include the library on your page, and it just works.

It smartly monitors various aspects of your page loading process – things like AJAX requests, how busy your JavaScript is, the document’s ready state, and even if certain elements have appeared on the page. Based on this monitoring, it intelligently updates the progress bar, giving your users a real-time visual indicator of how things are progressing.

Think of it as your website’s friendly “Please Wait” sign, but way cooler and more informative. It fills that awkward gap between the click and the content appearing, making the transition feel smoother and more professional.

Why Bother with a Loading Bar? It’s All About User Experience

You might wonder, “My site loads pretty fast, do I really need this?” While a progress bar won’t miraculously speed up your server response time or download speeds, it dramatically improves perceived performance.

Consider these points:

Benefits of Progress Bars
Benefits of Progress Bars
  • Reduced Anxiety: Users aren’t left staring at a blank screen, wondering if their click registered or if the site is broken.
  • Clear Feedback: They know the page is loading and can see the progress.
  • Professionalism: A smooth loading experience feels polished and indicates attention to detail.
  • Handling the Unexpected: Even on fast connections, unexpected delays can happen. A progress bar helps manage user expectations during these moments.

Pace.js makes implementing this UX enhancement incredibly easy, even if you’re brand new to JavaScript libraries.

Getting Started is a Breeze: Including Pace.js

This is where the magic begins. For most beginners, adding Pace.js is as simple as including two files in the <head> section of your HTML document. You’ll need the main pace.js file and a CSS file for the theme you choose (more on themes in a bit!).

It’s crucial to include these files as early as possible in your <head>. This allows Pace.js to start monitoring the page load right from the beginning.

Here’s a basic example of what your <head> might look like:

HTML

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Awesome Website</title>

    <script src="path/to/pace.min.js"></script>

    <link rel="stylesheet" href="path/to/pace-theme-default.min.css">

    <link rel="stylesheet" href="path/to/your-styles.css">
</head>

Important: You’ll need to download the pace.min.js file and the CSS theme file from the Pace.js distribution and place them in a location accessible by your HTML file (e.g., a js folder and a css folder). Update the path/to/... placeholders with the actual paths.

That’s it! Save your HTML file, open it in a browser, and watch Pace.js automatically add a progress bar as your page loads. Seriously, for many simple sites, zero additional code is needed!

For the More Technically Inclined (or Future Reference):

If you’re using module bundlers like AMD (Asynchronous Module Definition) or Browserify, the process is slightly different. You’ll require or import pace.js and then explicitly call pace.start() as early as possible in your application’s loading process. This ensures Pace.js is active before other parts of your application start loading resources.

JavaScript

// Example using AMD
define(['pace'], function(pace) {
    pace.start(); // Start Pace.js as soon as it's loaded
    // Your other application logic here
});

// Example using Browserify/CommonJS
const pace = require('pace-js');
pace.start(); // Start Pace.js
// Your other application logic here

Don’t worry if this looks confusing now. For beginners, the simple script and link tag method is the easiest way to get started.

Making it Yours: Themes!

One of the great things about Pace.js is that it comes with a variety of pre-designed themes. This means you don’t have to be a CSS wizard to make your progress bar look good. Pace.js provides several CSS files, each representing a different visual style for the progress bar.

To use a theme, you simply link to its corresponding CSS file in your <head> instead of the default one. For example, to use the “flat top” theme, you would link to pace-theme-flat-top.min.css.

HTML

<head>
  <script src="path/to/pace.min.js"></script>
  <link rel="stylesheet" href="path/to/pace-theme-flat-top.min.css">
</head>

You can explore the different theme CSS files included in the Pace.js download to see which style fits your website best. They range from simple bars to more complex indicators. Feeling creative? You can even design your own custom themes by writing CSS that targets the elements Pace.js creates (like .pace, .pace-progress, etc.).

How Does Pace.js Work Its Magic? The “Collectors”

You might be wondering how Pace.js knows how much of the page has loaded. It’s not actually psychic! It uses what it calls “collectors” – small bits of code that monitor different activities happening in your browser as the page loads. Pace.js combines information from these collectors to estimate the overall progress.

By default, Pace.js uses four main collectors:

Pace.js Collectors Hierarchy
Pace.js Collectors Hierarchy
  1. Ajax: This collector watches for any Asynchronous JavaScript and XML (AJAX) requests being made by your page. These are common for fetching data in the background without a full page refresh. Pace.js tracks their progress.
  2. Elements: This collector checks if specific elements you might be waiting for have appeared on the page. This can be useful if your page’s content is dynamically loaded.
  3. Document: This is a straightforward one. It checks the standard readyState of the browser’s document, which tells you if the HTML has been fully loaded and parsed.
  4. Event Lag: This is a bit more technical, but essentially, it checks if the browser’s main JavaScript execution thread is busy. High event lag can indicate that complex scripts are running, which might be part of the loading process.

Pace.js cleverly combines the information from these collectors, scaling and smoothing the progress updates to provide a visually appealing and reasonably accurate representation of the loading process.

Configuration: Basic Tweaks (Optional!)

While Pace.js is designed to work automatically, you might occasionally want to tweak its behavior. The good news is, you don’t need to configure anything to start, but if you do need to, it’s straightforward.

You can configure Pace.js by setting a global JavaScript variable called paceOptions before you include the pace.min.js file. This variable is an object containing the settings you want to change.

HTML

<head>
    <script>
        paceOptions = {
            // Disable the 'elements' collector
            elements: false,

            // Only show the progress on regular page navigation and AJAX page navigation,
            // not every single AJAX request that might happen later.
            restartOnRequestAfter: false
        };
    </script>
    <script src="path/to/pace.min.js"></script>
    <link rel="stylesheet" href="path/to/pace-theme-default.min.css">
    </head>

In this example, we’ve disabled the elements collector and changed how Pace.js reacts to AJAX requests using restartOnRequestAfter.

You can also put options directly on the script tag that includes pace.min.js using the data-pace-options attribute. This works similarly:

HTML

<head>
    <script data-pace-options='{ "ajax": false }' src="path/to/pace.min.js"></script>
    <link rel="stylesheet" href="path/to/pace-theme-default.min.css">
</head>

This is often useful if you have minimal configuration needed.

If you are using AMD or Browserify, you can pass your options directly to the pace.start() function:

JavaScript

define(['pace'], function(pace) {
    pace.start({
        document: false // Disable the document collector
    });
    // Your other application logic here
});

These configuration options allow you to fine-tune which parts of your page load Pace.js monitors, which can be helpful for specific scenarios or to avoid tracking certain types of requests.

Configuring the ‘Elements’ Collector:

If you do want to use the elements collector, you need to tell Pace.js which CSS selectors it should look for. Pace.js considers the elements test successful when each specified selector matches at least one element on the page.

JavaScript

paceOptions = {
    elements: {
        selectors: ['.my-main-content', '.footer-loaded'] // Pace waits for elements with these classes
    }
};

You can even include alternative selectors separated by a comma within a string. This is useful if there might be an error state where the primary element doesn’t appear, but an error message element does.

JavaScript

paceOptions = {
    elements: {
        selectors: ['.timeline,.timeline-error', '.user-profile,.profile-error']
        // This means: (either .timeline OR .timeline-error) AND (either .user-profile OR .profile-error)
    }
};

Pace.js will consider the elements test complete when at least one selector in each comma-separated group finds a match.

Automatic Restarts and How to Control Them

By default, Pace.js is designed to handle modern web navigation, including what’s called “pushState” or “replaceState” (common in single-page applications or when using AJAX to load content without a full page reload). When these events occur, Pace.js automatically restarts the progress bar to show the loading of the new content.

Most of the time, this is exactly what you want. However, you can disable this behavior if needed:

JavaScript

paceOptions = {
    restartOnPushState: false // Disable automatic restart on pushState/replaceState
};

Pace.js also, by default, restarts the progress bar if an AJAX request takes longer than a certain duration (500ms by default). This is helpful for showing progress on significant background data fetches during navigation. If you have many small, quick AJAX requests that aren’t critical to the perceived page load, you might want to disable this:

JavaScript

paceOptions = {
    restartOnRequestAfter: false // Disable automatic restart on prolonged AJAX requests
};

Even if you disable the automatic restarts, you can always trigger a restart manually whenever you need to by calling Pace.restart() in your JavaScript code.

Taking Control: The Pace.js API

While Pace.js is automatic, it also provides a simple Application Programming Interface (API) that you can use to interact with it directly using JavaScript. This is useful for more advanced scenarios where you need explicit control over the progress bar.

Here are the main methods available on the global Pace object (which becomes available after you include pace.min.js):

  • Pace.start(): Use this to explicitly show the progress bar and begin monitoring. This is called automatically if you include the script normally, but you might use it if you initially configured Pace.js to not start automatically or if you’re using AMD/CommonJS.
  • Pace.restart(): As mentioned before, this method resets the progress bar and starts it again from the beginning. This is often called automatically on navigation events, but you can call it manually after, for example, manually loading new content via AJAX.
  • Pace.stop(): This method hides the progress bar and stops the monitoring process. You might use this if you have a specific loading sequence that you want to manually control when the progress bar disappears.

You can call these methods in your own JavaScript code like this:

JavaScript

// Somewhere in your script after Pace.js has loaded
function loadNewContent() {
    Pace.restart(); // Restart the progress bar before loading new content
    // Code to load new content via AJAX or other means
}

// Later, when the content is fully loaded
function contentLoaded() {
    // Pace.js might detect this automatically, but you could manually stop if needed
    // Pace.stop();
    console.log("New content is visible!");
}

Explicitly Tracking or Ignoring Requests

Sometimes, you might have specific AJAX requests that you always want Pace.js to track, regardless of your general configuration. Conversely, you might have requests that you never want it to track (like background health checks or analytics pings). Pace.js provides methods for this:

  • Pace.track(function() { ... });: Any AJAX requests initiated inside the function you pass to Pace.track will be explicitly tracked by Pace.js, even if you have disabled AJAX tracking globally.
  • Pace.ignore(function() { ... });: Any AJAX requests initiated inside the function you pass to Pace.ignore will be explicitly ignored by Pace.js, even if you have AJAX tracking enabled globally.

JavaScript

// Example: Force tracking a specific request
Pace.track(function() {
    $.ajax({ url: '/important-data' }); // This request will be tracked
});

// Example: Ignore a background request
Pace.ignore(function() {
    $.ajax({ url: '/health-check' }); // This request will be ignored
});

You can also configure Pace.js to ignore AJAX requests based on their URL using the ignoreURLs option in paceOptions.ajax:

JavaScript

paceOptions = {
    ajax: {
        ignoreURLs: ['/analytics', /\/api\/background\/.*/] // Ignore URLs containing '/analytics' or matching the regex
    }
};

This provides fine-grained control over which network activities influence the progress bar.

Listening In: Pace.js Events

Pace.js also fires several events that you can listen for in your JavaScript code. This allows you to react when the progress bar starts, stops, finishes, or is hidden.

Here are the main events:

  • start: Fired when Pace.js begins monitoring and the progress bar is shown (either initially or as part of a restart).
  • stop: Fired when Pace.js is manually stopped via Pace.stop().
  • restart: Fired when Pace.js restarts the progress bar (either manually or automatically).
  • done: Fired when Pace.js believes the loading process is complete (the progress bar reaches 100%).
  • hide: Fired when the progress bar actually disappears from the screen. This might happen slightly after the done event, depending on configuration options like ghostTime (how long it lingers at 100%) and minTime (minimum display time).

You can bind functions to these events using the Pace.on() method:

JavaScript

Pace.on('done', function() {
    console.log('Pace.js says loading is complete!');
    // Maybe fade in your main content here
});

Pace.on('hide', function() {
    console.log('The progress bar is now hidden.');
});

You can unbind event handlers using Pace.off(event, handler) and bind a handler to only the next occurrence of an event using Pace.once(event, handler). These methods work similarly to event listeners in many other JavaScript libraries.

Under the Hood: Dependencies, Support, and Size

One of the best things about Pace.js, especially for beginners or those working on projects with minimal dependencies, is that it has NO DEPENDENCIES! You don’t need jQuery or any other library for Pace.js to work.

Support: Pace.js is designed to work in a wide range of browsers, including older ones like IE8+ (in standards mode), Firefox 3.5+, Chrome, Safari 4+, Opera 10.5+, and all modern mobile browsers. This makes it a robust choice for ensuring a good experience across different user environments.

Size: The pace.js file itself is incredibly small, only about 4kb when minified and gzipped. The themes are also tiny, ranging from 0.5kb to 4kb. This means adding Pace.js to your site won’t significantly impact your page’s loading speed – which would be counterproductive for a loading bar!

Where to Get Help and Contribute

If you run into any issues or have questions, the best place to start is the official Pace.js documentation, which was used as a reference for this post: https://codebyzach.github.io/pace/docs/

The documentation provides more detailed information on configuration options, the API, and themes.

Pace.js is open source, hosted on GitHub. If you find a bug or have an idea for improvement, you can create an issue or even submit a pull request on the project’s GitHub page. Contributing to open source is a great way to learn and give back to the developer community!

Conclusion: A Simple Win for User Experience

Adding a progress bar to your website might seem like a small detail, but it has a significant impact on user perception and overall experience. Pace.js makes implementing this feature incredibly easy, often requiring just two lines of HTML.

Its automatic nature, combined with lightweight size and theme options, makes it an excellent choice for beginners looking to enhance their websites without diving into complex JavaScript. By providing clear visual feedback during the loading process, you make your website feel faster, more responsive, and more professional.

Ready to Give it a Try?

Download Pace.js today and follow the simple steps outlined above to add an automatic loading bar to your website. Experiment with different themes and see the difference it makes! It’s a quick win for your users and a testament to how small details can lead to a much better online experience.


Learn More About Making Websites User-Friendly!

Improving user experience goes beyond loading bars. If you’re a beginner looking to understand more about creating great websites, consider checking out a book on front-end web development or user interface/user experience design. A great resource can help you build a strong foundation in creating engaging and intuitive web experiences.

3243
3

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply