AJAX preloader

suggest change

Here’s a way to show a GIF preloader while an AJAX call is executing. We need to prepare our add and remove preloader functions:

function addPreloader() {
  // if the preloader doesn't already exist, add one to the page
  if(!document.querySelector('#preloader')) {
    var preloaderHTML = '<img id="preloader" src="https://goo.gl/cNhyvX" />';
    document.querySelector('body').innerHTML += preloaderHTML;
  }
}

function removePreloader() {
  // select the preloader element
  var preloader = document.querySelector('#preloader');
  // if it exists, remove it from the page
  if(preloader) {
    preloader.remove();
  }
}

Now we’re going to look at where to use these functions.

var request = new XMLHttpRequest();

Inside the onreadystatechange function you should have an if statement with condition: request.readyState == 4 && request.status == 200.

If true: the request is finished and response is ready that’s where we’ll use removePreloader().

Else if false: the request is still in progress, in this case we’ll run the function addPreloader()

xmlhttp.onreadystatechange = function() {

  if(request.readyState == 4 && request.status == 200) {
    // the request has come to an end, remove the preloader
    removePreloader();
  } else {
    // the request isn't finished, add the preloader
    addPreloader()
  }

};

xmlhttp.open('GET', your_file.php, true);
xmlhttp.send();

Feedback about page:

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


AJAX:
* AJAX preloader

Table Of Contents
11 Arrays
12 Objects
14 Classes
16 Map
17 Set
24 Loops
27 Date
29 Scope
30 AJAX
35 Cookies
41 JSON
44 Fetch
45 Modules
46 Screen
64 Console
68 Symbols
73 Modals
76 Events
86 Proxy
89 WeakMap
90 WeakSet
102 Tilde