AJAX preloader
suggest changeUse a loading indicator while an asynchronous request is in progress. Creating DOM nodes directly avoids reparsing the document and preserves existing event listeners:
function addPreloader() {
if (!document.querySelector('#preloader')) {
const preloader = document.createElement('img');
preloader.id = 'preloader';
preloader.src = '/images/loading.gif';
preloader.alt = 'Loading';
document.body.append(preloader);
}
}
function removePreloader() {
document.querySelector('#preloader')?.remove();
}
Use finally so the indicator is removed whether the request succeeds or fails:
async function loadData(url) {
addPreloader();
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return await response.json();
} finally {
removePreloader();
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents