Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

You can display a preloader element while waiting for a server response using fetch by following these steps:

  1. Create a variable that references the element to be displayed as the preloader.

    const preloader = document.querySelector('.preloader');
    
  2. Before making the fetch request, display the preloader element.

    preloader.style.display = 'block';
    
  3. Make the fetch request as you would normally.

    fetch('/api/data')
     .then(response => response.json())
     .then(data => {
       // handle the data returned
     })
     .catch(error => {
       // handle any errors
     });
    
  4. After the request is complete, hide the preloader element.

    preloader.style.display = 'none';
    

Here's the complete example:

const preloader = document.querySelector('.preloader');

preloader.style.display = 'block';

fetch('/api/data')
  .then(response => response.json())
  .then(data => {
    // handle the data returned

    preloader.style.display = 'none';
  })
  .catch(error => {
    // handle any errors

    preloader.style.display = 'none';
  });