AJAX preloader

suggest change

Use 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();
  }
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents