Loading State

The loading state feature allows you to display a loading spinner while content is being fetched. This is particularly useful for slow network connections or when content takes a while to load. The loading state does not calculate the loading time; instead, it simply notifies the page when the loading process starts and finishes. To know when the loading process starts and finishes, you can use two different approaches.

Using the Loading State API

The loading state API provides two methods to handle the loading process: startLoading() and finishLoading(). These methods allow you to control the loading state of the page manually.

Additionally, you can listen for the loading-started and loading-finished events on the document to be notified when the loading process begins and ends.

Using the Loading State API

    papeljs.startLoading();
    // Fetch content
    papeljs.finishLoading();
        
Listening for loading events

    document.addEventListener('loading-started', () => {
      console.log('Loading started');
    });

    document.addEventListener('loading-finished', () => {
      console.log('Loading finished');
    });
        

Using the Loading CSS classes

The loading state feature also provides two CSS classes that you can use to style the loading spinner: .before-loading, .is-loading and .after-loading. These classes are added to the <body> element when the loading process starts and finishes, respectively.

You can use these classes to display a loading spinner or any other loading indicator on your page. For example, you can hide the spinner when the loading process starts and show it when the loading process finishes. the following CSS code shows how to use these classes to display a loading spinner.

Using the Loading CSS classes

    .loading-spinner {
      display: none;
    }

    .before-loading .loading-spinner {
      display: block;
      opacity: 0;
    }

    .is-loading .loading-spinner {
      display: block;
      opacity: 1;
    }

    .after-loading .loading-spinner {
      display: block;
      opacity: 0;
    }
        

Using Third-Party Libraries

If you prefer to use a third-party library to handle the loading state, you can do so by listening for the loading-started and loading-finished events on the document. This way, you can integrate any library that provides a loading state feature with papeljs.

For example, you can use the popular library Pace to display a loading bar on your page.