0

I have an AJAX call whose reponse will feed some HTML into a DIV's innerHTML.

The response can contain images, and I'd like to have all these images loaded before my custom loading-div will hide.

I want to do this in vanilla JS. Unfortunately every question I've found here so far does it via jQuery.

I've tried adding an onload Event Listener to both the DIV and the xhttp object, but neither works. The loader disappears as soon as the HTML code is received and inserted, and then the user can witness each image loading individually.

   document.getElementById("pageloader").className = "fadein";
   var poststring = "&page="+encodeURIComponent(page);
   var xhttp = new XMLHttpRequest();
   xhttp.addEventListener("load", function() {
      document.getElementById("pageloader").className = "fadeout";
   });
   xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
         document.getElementById("content").innerHTML = this.responseText;
      }
   };
   xhttp.open("POST", "myajax.php", true);
   xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
   xhttp.send(poststring);
Krupal Panchal
  • 1,428
  • 2
  • 8
  • 22
MiK
  • 848
  • 2
  • 16
  • do you have some code samples? – Medet Tleukabiluly Nov 12 '19 at 16:45
  • Added the xhttp. – MiK Nov 12 '19 at 16:48
  • You're not calling your xhttp request, if you just didn't include that part, try using other listener, something like `onEndLoad`, `loadend`, `loadfinish`, etc. Stick with the specs, because you're listening for load, but not for load finish – Medet Tleukabiluly Nov 12 '19 at 16:49
  • I just hadn't included it. Loadend, etc. doesn't seem to work. https://xhr.spec.whatwg.org/#events doesn't look like anything here fits, I'm guessing the event listener must be attached to something other than the xhttp object. – MiK Nov 12 '19 at 16:57
  • try this https://stackoverflow.com/a/19247992/2308005 – Medet Tleukabiluly Nov 12 '19 at 16:59
  • https://perishablepress.com/3-ways-preload-images-css-javascript-ajax/ seems to have an example of what you want to do. – Deadron Nov 12 '19 at 17:07

0 Answers0