Vilx- Vilx- - 2 years ago 105
Javascript Question

How to check if DOM is ready without a framework?

The question is so like a zillion others here and on the web - How to check if DOM has loaded in Javascript? But here's the catch:

  • Without using a framework like jQuery etc;

  • Without knowing if your script has been loaded via a statically placed
    tag or via some other Javascript much later after the DOM has already loaded.

Can this be done more or less reliably and with cross-browser compatibility?

Added: Let me clarify: I'm writing a standalone .JS file which can be included in arbitrary webpages. I want to execute code AFTER the DOM has been loaded. But I don't know HOW my script will be included. It could be by placing a
tag (in which case the traditional
or DOM-readiness solutions will work); or it could be loaded via AJAX or some other means, much later after the DOM is already loaded (so the previously mentioned solutions will never fire).

Answer Source

The document.readyState property can be used to check if the document is ready:

if(document.readyState === "complete") {
  //Already loaded!
else {
  //Add onload or DOMContentLoaded event listeners here: for example,
  window.addEventListener("onload", function () {/* your code here */}, false);
  //document.addEventListener("DOMContentLoaded", function () {/* code */}, false);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download