Steps for creating an effective page preloader

My website involves fetching data upon loading. I am working on implementing a preloader that will be displayed until the site fully loads and all initial requests are completed.

I've come across tutorials for preloaders that rely on setting a time interval, but I want my loader to genuinely wait for the page to finish loading.

Do you have any advice on how to achieve this?

Answer №1

Utilize the power of async functions

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

async function executeAsyncFunction() {
  console.log('beginning execution');
  const result = await waitTwoSeconds();
  console.log(result);
  // expected output: "completed"
}

window.addEventListener('load', async (event) => {
  let isPageLoading = true 
  // By tracking loading state, you can decide when to display a loader

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

  isPageLoading = false
  console.log('page has finished loading');
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

substitute elements within an array using elements from a different array

Looking to swap object(s) in an array with another array while maintaining the original order. Here is arrayOne: [ { "color": "#f8edd1", "selected": true }, { "color": "#d88a ...

MongoDB Server Selection Error: Connection Timeout Causing Intermittent Unhandled Promise Rejection

I keep encountering this error at random times. Here is the stack trace: App deployed on vercel is talking to Atlas mongodb (free tier) Nodejs - 18.16.1 nextjs 13 mongodb package version - 5.8.1 ERROR Unhandled Promise Rejection {"errorType&qu ...

Leveraging the power of Node with Knex and Bookshelf to implement a dynamic where

I am in the process of updating a query that retrieves model instances with related items. The goal is to dynamically change the where clause based on whether a search term or an ID is provided. When I make the adjustment as shown below: return db.model( ...

What's causing the issue with the rot-corona animation not functioning properly?

I am currently working on a project related to the coronavirus, and I am having trouble with the animation "rot-corona." I need it to rotate 360 degrees every 3 seconds. Please note that Bootstrap 4 is being used in this project. Code /* SCSS */ #rota ...

Ensure that JavaScript finishes the animation before transitioning to the next step

Currently, I am developing a basic rotator that cycles through three pieces of advice on a website. My goal is to create a smooth fade in and out effect by adding and removing classes. While testing in the JavaScript debugger, everything runs smoothly as i ...

Is it possible for me to designate a specific class for the rev value?

<a href="img1.jpg" rel="zoom-id:bike" rev="img1.jpg"> <img src="" class="img-thumb"/></a> Shown above is a snippet of HTML code. I wonder if it's possible for the attribute rev="img1.jpg" to have a class that only affects the s ...

How to utilize string interpolation in Vue 3 template attribute with quotation marks

I'm struggling to make the method buildAbbrToolTip() utilize the dynamic data from column.m_parse_hi in order to display the correct text definition for an abbreviation in the tooltip. Currently, I'm encountering a console error that says TypeEr ...

Understanding the Code for Responsive Web Typography with line-height in ems

I am currently trying to delve into the CSS calculation process behind the styling in the code snippet provided. This code snippet is from a responsive WordPress theme, and I am struggling to decipher how the em values for the line-height of the <h> ...

Trouble with $.ajaxSetUp occurring before sending the data

$.ajaxSetup({ beforeSend: function(jqXHR, settings) { if(settings.type == "POST") settings.data = $.extend(settings.data, {test:"One" }); return true; } }); Hello there, I am trying to include the data {test:"One"} in ...

I seem to be facing some difficulty in dynamically calling my buttons in AngularJS

Can you assist me in solving this problem? I am new to Angular and just starting out. Initially, there is only one button on load called "Add list". When the user clicks on this button, they are able to add multiple lists. Each list contains a button labe ...

Angular module now equipped with web worker for independent operation

My goal is to create a standalone AngularJS module that utilizes web workers for handling heavier processing tasks. This module will be integrated into an Angular web application that I am currently developing, as well as potentially other projects. I env ...

Tips on formatting dates in a Material UI text field

<TextField name="BalDueDate" format="MM/dd/yyyy" value={basicDetails.BalDueDate.slice(0,10)} onChange={event => { ...

Mongoose and Bcrypt Login Issue

Encountering an issue with logging in using mongoose and bcrypt. The error received: TypeError: cb is not a function The model being used: const mongoose = require('mongoose'); const Schema = mongoose.Schema; const bcrypt = require('bc ...

The property '_renderItem' cannot be defined as undefined

Seeking assistance with my code... Could someone please help? $(document).ready(function() { //$('#search input[name="filter_name"]').attr("x-webkit-speech", "x-webkit-speech") $('#search input[name="input-search-menu"]').autocompl ...

Make sure the div is positioned at the center of the screen with a set width, and ensure that

Is there a way to have three divs align next to each other, with the side divs filling up the remaining space equally? <div class="second_bar"> <div class="status_border_left"> </div><div class="nav_bar"> ...

Ways to customize the appearance of the Next/Prev Button in Griddle

Here is the scenario that has been implemented: nextClassName={'text-hide'} nextText={''} nextIconComponent={ <RaisedButton label='Next' />} As a result, a Next Button with a wrapper div above the but ...

CSS isn't functioning properly on 000webhost

Recently, I launched a basic website on 000webhost. The index.html file I uploaded looks like this: <!DOCTYPE html> <html lang="en> <head> <title>Tabs</title> <meta charset="utf-8"> ...

Achieve horizontal bar movement by utilizing google.visualization.DataTable in a left-to-right motion

I am exploring the possibility of reversing the direction of a chart(bar) using google.visualization.DataTable. In the current setup, the bar progresses from left to right, but I wish for it to move from right to left instead. Below is what I have attempte ...

What is the reason that columns do not float in Bootstrap when there are no rows?

I have been doing some research into Bootstrap and have come across the following resources: What is the purpose of .row in Bootstrap? and Despite reading these links, I am still struggling to understand why my columns do not float left as expected in th ...

A guide on scheduling automatic data insertion in mongoose.js

I'm working on a website with Node.js and Mongoose, and I could use some guidance on how to automatically insert data into Mongoose with Node.js at specific times. For example, at the end of each month, I want my current data to be stored in the Mongo ...