You can utilize the JavaScript Window's 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:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>$(document).ready() Equivalent without jQuery</title>
<script>
document.addEventListener("DOMContentLoaded", function(){
// Apply some style on paragraph
document.getElementsByTagName("p")[0].style.background = "yellow";
console.log("DOM has been fully loaded and parsed.");
});
</script>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a simple paragraph of text.</p>
</body>
</html>
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.
Use the
DOMContentLoaded
EventYou can utilize the JavaScript Window's
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:
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.
need an explanation for this answer? contact us directly to get an explanation for this answer