1 | initial version |
You can display a preloader element while waiting for a server response using fetch
by following these steps:
Create a variable that references the element to be displayed as the preloader.
const preloader = document.querySelector('.preloader');
Before making the fetch
request, display the preloader element.
preloader.style.display = 'block';
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
});
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';
});