0

I was wondering what is the best method in order to fire an event when all DOM is loaded. In particular, suppose that the HTML page contains a number of AJAX request. Is it enough to use:

window.onload = function() { };

or:

window.addListener("DOMCreated", function() { });

The answer should be "no", since I've tried to use these two functions, but when I try to do document.getElementById("id"), I always got a null.

Ah, I cannot use jQuery.

Surcle
  • 572
  • 1
  • 5
  • 15

1 Answers1

1

What you want is the DOMContentLoaded event.

document.addEventListener("DOMContentLoaded", function(){ ... });

See Difference between DOMContentLoaded and load events

daddygames
  • 1,880
  • 1
  • 11
  • 18
  • It does not work. I don't think that it waits for other AJAX calls – Surcle Sep 20 '18 at 14:02
  • You need to post how you are calling the AJAX. XMLHttpRequest is built so you can perform actions as soon as the request returns, which sounds what you really want. – daddygames Sep 20 '18 at 14:07
  • If I set a timeout, after 5 seconds the element is not null, but it is if I use the function that you suggested. – Surcle Sep 21 '18 at 10:27
  • See https://stackoverflow.com/questions/8567114/how-to-make-an-ajax-call-without-jquery. In the condition (xmlhttp.status == 200) you take the action on the page that you want to happen once the AJAX request has completed. You don't want to use timeouts when you don't know how long the AJAX request will take to return. – daddygames Sep 24 '18 at 14:44