How to programmatically control a loader

In this article you will learn how to programmatically control a loader. You can play and pause a loader whenever you need it.

You will need to have some developer knowledge when attempting this. Feel free to contact us if you'd like some extra information.

When you install the loader component or snippet, you will see undermentioned code in the JavaScript panel.

(() => {
let pageloader = false;
pageloader = {[:cssdata:]}?.pageloader;

if (pageloader) {
document.documentElement.style.setProperty('--sm-loader-display-sm-unique-style', 'flex');
}

document.addEventListener('DOMContentLoaded', e => {
const smLoader = new SM_Loader({
id: 'sm-unique-id',
[:cssdata:]
});
});
})();

The first part of this code, creates a pageloader when needed. We are more interested in the second part however, where the smLoader instance is being created.

You can programmatically control the loader through the following methods:

  • play()
  • stop()
  • toggle()

The code example below will demonstrate this by executing these actions:

  1. The loader will play when the content has loaded.
  2. The loader will stop 1 second after the content has loaded.
  3. The loader will play again (with a toggle) 3 seconds after the loader has stopped.
document.addEventListener('DOMContentLoaded', e => {
const smLoader = new SM_Loader({
id: 'sm-unique-id',
[:cssdata:]
});

smLoader.play();
setTimeout(() => smLoader.stop(), 1000);
setTimeout(() => smLoader.toggle(), 3000);
});