mmm42
mmm42

Reputation: 47

How to properly make a preloader a page

I have a site which performs some data-fetching on load. I am trying make a preloader to this site that is only shown for however long it takes the site to fully load and complete any initial requests.

I've seen tutorials for preloaders where they just set a time interval on the loader, but I'm trying to make the loader actually wait for the page to load.

Any tips?

Upvotes: 2

Views: 451

Answers (1)

Charles Lavalard
Charles Lavalard

Reputation: 2321

You can use async functions

function resolveAfter2Seconds() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('resolved');
    }, 2000);
  });
}

async function asyncCall() {
  console.log('calling');
  const result = await resolveAfter2Seconds();
  console.log(result);
  // expected output: "resolved"
}

window.addEventListener('load', async (event) => {
  let loading = true 
  // this loading value helps you to know when to show your loader

  await console.log('page is loading');
  await asyncCall()

  loading = false
  console.log('page is loaded');
});

Upvotes: 4

Related Questions