PACE Automatic Web Page Progress Bar

repository·master·Indexed 12 days ago

https://github.com/codebyzach/pace

An automatic progress bar for websites that monitors AJAX requests, event loop lag, document ready state, and specific DOM elements to provide visual feedback during page loads and navigation. Version 1.2.4 includes a public API for manual control via Pace.start(), Pace.stop(), and Pace.restart(), as well as the ability to track or ignore specific requests using Pace.track() and Pace.ignore().

Tokens
2.5K
Snippets
9
Records
12
Agent score
47%

What's inside PACE

  1. How PACE collectors work

    master

    Collectors are the mechanisms that gather progress information. PACE includes four default collectors:

    • Ajax: Monitors all AJAX requests.
    • Elements: Checks for the existence of specific elements.
    • Document: Checks the document.readyState.
    • Event Lag: Checks for event loop lag.

    To add custom sources, add objects to paceOptions.extraSources. Each source must have either a .progress property or an .elements property (which is a list of objects containing .progress properties). PACE handles the scaling automatically.

    paceOptions = {
      ajax: false,
      document: false,
      eventLag: false,
      elements: {
        selectors: ['.my-page']
      }
    };
  2. Manage PACE restart rules

    master

    PACE can automatically restart the progress bar under certain conditions:

    • PushState: By default, it restarts on pushState or replaceState (common in AJAX navigation). Disable this with restartOnPushState: false.
    • Long Requests: It can restart on every AJAX request that lasts longer than a specific threshold. Disable this with restartOnRequestAfter: false to avoid showing progress for background tasks like precaching.

    You can also trigger a restart manually using Pace.restart().

  3. Install and use PACE

    master

    To use PACE, include pace.js and a theme CSS file in your <head> as early as possible. PACE automatically monitors AJAX requests, event loop lag, document ready state, and page elements to manage a progress bar.

    If you are using AMD or Browserify, you must require pace.js and call pace.start() as early as possible in the loading process.

    <head>
      <script src="https://cdn.jsdelivr.net/npm/pace-js@latest/pace.min.js"></script>
      <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/pace-js@latest/pace-theme-default.min.css">
    </head>
  4. Track or ignore specific AJAX requests

    master

    By default, PACE shows AJAX requests that are part of a page load or last longer than 500ms. You can override this behavior manually:

    To ignore a request: Wrap the request in Pace.ignore(). To force tracking a request: Wrap the request in Pace.track(). To ignore URLs by pattern: Use the ajax.ignoreURLs option in your configuration.

    Example of ignoring/tracking:

    // Ignore a specific request
    Pace.ignore(function() {
      $.ajax({
        url: '/background-task'
      });
    });
    
    // Force track a specific request
    Pace.track(function() {
      $.ajax({
        url: '/important-data'
      });
    });

    Example of URL pattern ignoring:

    Pace.options = {
      ajax: {
        ignoreURLs: ['some-substring', /some-regexp/]
      }
    }
    Pace.ignore(function() {
      $.ajax(...);
    });
  5. Configure PACE options

    master

    PACE is automatic, but you can customize its behavior using one of three methods:

    1. Global Object: Set window.paceOptions before loading the script.
    2. Script Tag: Use the data-pace-options attribute on the script tag (must be a JSON string).
    3. Programmatic: Pass options directly to pace.start() when using AMD or Browserify.

    Common options include:

    • ajax: Boolean or object (e.g., { ignoreURLs: [...] }) to control AJAX monitoring.
    • elements: Boolean or object with selectors to monitor specific DOM elements.
    • document: Boolean to enable/disable monitoring the document.readyState.
    • eventLag: Boolean to enable/disable monitoring event loop lag.
    • restartOnPushState: Boolean to control if the bar restarts on pushState events.
    • restartOnRequestAfter: Boolean to control if the bar restarts on AJAX requests exceeding a certain duration.
    • className: String to add a custom CSS class to the progress bar.
    // Method 1: Global object
    paceOptions = {
      elements: false,
      restartOnRequestAfter: false
    };
    
    // Method 2: Script tag
    // <script data-pace-options='{ "ajax": false }' src="..."></script>
    
    // Method 3: Programmatic (AMD/Browserify)
    define(['pace'], function(pace){
      pace.start({
        document: false
      });
    });
  6. PACE Public API Reference

    master

    The following methods are exposed on the Pace object:

    • Pace.start(): Shows the progress bar and begins updating. (Called automatically if not using AMD/CommonJS).
    • Pace.restart(): Shows the progress bar (if hidden) and resets progress from scratch.
    • Pace.stop(): Hides the progress bar and stops all updates.
    • Pace.track(callback): Explicitly tracks the requests wrapped in the callback.
    • Pace.ignore(callback): Explicitly ignores the requests wrapped in the callback.
    • Pace.on(event, handler, [context]): Binds an event listener.
    • Pace.off(event, [handler]): Unbinds an event listener.
    • Pace.once(event, handler, [context]): Binds an event listener that triggers only once.
  7. PACE Events

    master

    PACE emits the following events which can be listened to via Pace.on():

    • start: Triggered when PACE initially starts or restarts.
    • stop: Triggered when PACE is manually stopped or as part of a restart.
    • restart: Triggered when PACE is restarted (manually or via AJAX/pushState).
    • done: Triggered when progress is finished.
    • hide: Triggered when the progress bar is hidden (may occur after done based on ghostTime and minTime).
  8. Configure Element selectors for progress

    master

    The elements collector allows you to define specific selectors that, when present, signal that the page has rendered. You can use comma-separated selectors to handle error states. PACE considers the test successful when each selector group matches something. For example, if you provide '.timeline, .timeline-error', the progress bar considers the element 'found' if either .timeline OR .timeline-error exists.

    paceOptions = {
      elements: {
        selectors: ['.timeline, .timeline-error', '.user-profile, .profile-error']
      }
    }
  9. Ignore or force tracking for specific operations

    master

    You can wrap specific code blocks to prevent them from triggering the progress bar or to force them to be tracked.

    • Pace.ignore(fn): Executes the function fn without triggering any progress updates (e.g., for background tasks).
    • Pace.track(fn): Forces the function fn to be tracked by the AJAX monitor, even if the request method or URL would normally be ignored.
    // This request will NOT trigger the progress bar
    Pace.ignore(() => {
      fetch('/api/silent-request');
    });
    
    // This request WILL trigger the progress bar even if it's a POST or ignored URL
    Pace.track(() => {
      fetch('/api/important-request', { method: 'POST' });
    });
  10. Listen to PACE progress and lifecycle events

    master

    PACE extends the Evented prototype, allowing you to attach listeners to various lifecycle and progress events.

    Available events:

    • start: Triggered when the progress bar starts.
    • progress: Triggered when the progress value changes. Receives the current progress percentage as an argument.
    • change: Triggered when the progress value changes (similar to progress).
    • restart: Triggered when the progress bar is restarted.
    • stop: Triggered when the progress bar is stopped.
    • done: Triggered when all monitored sources have reached 100%.
    • hide: Triggered when the progress bar is hidden after completion.
    // Listen for progress updates
    Pace.on('progress', function(progress) {
      console.log('Current progress: ' + progress + '%');
    });
    
    // Listen for completion
    Pace.on('done', function() {
      console.log('Loading finished!');
    });
    
    // Listen for a single event
    Pace.once('start', function() {
      console.log('PACE has started');
    });
  11. Stop and restart the PACE progress bar

    master

    Use Pace.stop() to halt monitoring and destroy the progress bar element. Use Pace.restart() to stop the current session and immediately start a new one. These methods trigger the stop and restart events respectively.

    // Stop the progress bar
    Pace.stop();
    
    // Restart the progress bar
    Pace.restart();
  12. Start the PACE progress bar

    master

    To begin monitoring and displaying the progress bar, call Pace.start(). You can pass an optional configuration object to override default settings. If startOnPageLoad is set to true (the default), PACE will attempt to start automatically when the script is loaded.

    Note: PACE requires a target element (defaulting to body) to inject the progress bar. If the target is not found, it will retry after a short delay.

    // Start with default options
    Pace.start();
    
    // Start with custom options
    Pace.start({
      target: '#progress-container',
      className: 'my-custom-bar'
    });