WebMasterCampus
WEB DEVELOPER Resources

jQuery Document Ready Equivalent Using JavaScript

Learn how to create jQuery document ready equivalent using Javascript


This is an alternative way to implement jQuery document ready function using Javascript. In this we need to make sure that to execute Javascript code when DOM is ready.

Why we need this?

Let’s take a scenario if you are building a small feature that can easily build without jQuery so, why we we would load the jQuery library if we can manage with vanila Javascript?

jQuery document ready Syntax

$(document).ready(function(){

      //do work
});

jQuery Document Ready Equivalent using Javascript

The following function will only fire when DOMContentLoaded event will be loaded. It’s equivalent of jQuery’s $(document).ready() method. Although, it fires before all page assets are loaded (CSS, images, etc.)

Learn more about DOMContentLoaded Event

Example 1


document.addEventListener("DOMContentLoaded", function(event) { 
  //do work
});

Example 2

Learn more about Document.readyState


<h1>Javascript Document Ready Equivalent Without Jquery</h1>
<div id="result"></div>

<script>

function ready(callback){
  // in case the document is already rendered
  if (document.readState != "loading")   
    callback();
  else  // modern browsers
    document.addEventListener('DOMContentLoaded', callback);
}


ready(function(){  
  document.getElementById('result').innerHTML = "Content loaded by DomLoad ";
});

</script>
Created with love and passion.