1

I'm loading several div with innerHTML in a main page using ajax (xmlhtthrequest is open with 'asynchronous') because the html for each div is generated with php by the server. After the full page is loaded, including the divs, I need to execute additional scripts on the full page. I don't want to put this additional scripts in the

    xhr.onreadystatechange = function() {
      if (this.readyState == 4) {
        if (this.status == 200){
          document.getElementById(div).innerHTML = this.responseText;
          //additional_js_code;
        }
      }
    }

bloc of the ajax request but instead at the end on the main page. This is because this additional code is not specific to the html loaded in the div. At the end of the main page, I write

 document.addEventListener("readystatechange", function(event){
   if(document.readyState == 'complete'){
     additional_js_code;
   } 
 });

But the 'complete' event is usually fired before all the divs have been loaded. Is there a way to detect the 'readyState' of all the ajax requests outside the xhr.onreadystatechange function ??

  • There are many ways to do this. You could use promises, or custom event listeners, or maintain state and set a timeout loop. Do you have a preference? – Jason Nichols Mar 08 '18 at 17:40
  • I'm just starting with the event listeners, and I would say they are the cleanest solution. I don't now the promise object at all. I'll try to have a look. – Laurent Mortier Mar 08 '18 at 23:09

0 Answers0