Answer: Use the
DOMContentLoaded event to construct
$(document).ready() equivalent without jQuery. This event fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.
Let's take a look at the following example to understand how it works:
ExampleTry this code »
<title>$(document).ready() Equivalent without jQuery</title>
// Apply some style on paragraph
document.getElementsByTagName("p").style.background = "yellow";
console.log("DOM has been fully loaded and parsed.");
<h1>This is a heading</h1>
<p>This is a simple paragraph of text.</p>
Note that the
DOMContentLoaded is different from
load event which is fired when the whole page has loaded. The
load event should only be used when you want to detect a fully-loaded page including all the dependent resources such as CSS, images, etc.
Here are some more FAQ related to this topic: