Q:

jQuery $(document).ready() Equivalent in JavaScript

0

jQuery $(document).ready() Equivalent in JavaScript

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use the DOMContentLoaded Event

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Set or Unset a Cookie with jQuery... >>
<< How to Get Class List of an Element with jQuery...