How to Check Document Ready in Javascript

Use-Cases of this Tutorial

  • Know when HTML gets loaded and DOM is ready for manipulation.
  • Implement jQuery's ready() method in pure Javascript.

We can find whether the document is ready by listening to the DOMContentLoaded event.

document.addEventListener('DOMContentLoaded', function() {
	// DOM ready for manipulation
});

When DOMContentLoaded is fired, note that :

  • HTML has been loaded and parsed. DOM is ready for manipulation
  • External stylesheets may not be loaded
  • Images may not be loaded
  • <script> tags have been loaded and executed (although scripts with async attribute are not required to be loaded)
  • If a <script> required to read or recalculate CSS values of an element, the related stylesheet was loaded as well
  • Iframes may not be loaded

Tips to Ready the Document Faster

  • Use async attribute for <script> tags.
  • If it is not possible to use async scripts, then avoid reading or recalculating CSS value of an element in the <script>
Loading Comments