WEB TUTORIALS
PRACTICE EXAMPLES
HTML REFERENCES
CSS REFERENCES
PHP REFERENCES

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

Topic: JavaScript / jQueryPrev|Next

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.


Related FAQ

Here are some more FAQ related to this topic:

Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties