How to Run JavaScript After DOM is Loaded Without jQuery đ[All Method]ī¸
![How to Run JavaScript After DOM is Loaded Without jQuery đ[All Method]ī¸](https://howisguide.com/wp-content/uploads/2022/02/How-to-Run-JavaScript-After-DOM-is-Loaded-Without-jQuery-All-Method.png)
The blog is about How to Run JavaScript After DOM is Loaded Without jQuery & provides a lot of information to the novice user and the more seasoned user. What should you do if you come across a code error! Let’s get started on fixing it.
Question: What is the best solution for this problem? Answer: This blog code can help you solve errors How to Run JavaScript After DOM is Loaded Without jQuery. Question: What are the reasons for this code mistake and how can it be fixed? Answer: You can find a solution by following the advice in this blog.
Weâve all used jQueryâs .ready()
function:
$("document").ready(function () {});
This has been the simplest, cross-browser compatible way to ensure that our page is loaded and ready to be accessed and modified.
What if itâs 2022, and we donât use jQuery anymore?
How can we do this is plain JavaScript?
Suppose we have this function that we want to run once the DOM is accessible to us:
const onReady = () => {
console.log("DOM is available!");
}
The Easiest Way: place script at the end of body
The fastest way to go about this in JavaScript is to run a self-executing function in a script appended at the end of the <body>
element.
<!doctype html>
<html>
<head></head>
<body>
<!-- Some HTML -->
<script>
(function() {
onReady();
})();
</script>
</body>
</html>
Because the script runs at the end of the <body>
element, it will only run after all the DOM is processed and loaded onto the page.
This is compatible on all browsers.
The Alternative Way: use a DOMContentLoaded
event listener
Suppose we donât want our script to lie at the end of the <body>
element. In this case, we can write this areWeReady()
function to check if the DOM is already available.
If so, weâll call the input function on the next available cycle.
If not, weâll add an event listener that will wait for the DOM to be loaded.
function areWeReady(fn) {
if (document.readyState === "complete" || document.readyState === "interactive") {
setTimeout(fn, 1);
} else {
document.addEventListener("DOMContentLoaded", fn);
}
}
We can invoke this function and then pass in onReady()
from above.
areWeReady(onReady());
The great thing here is that this will work on modern browsers (Chrome, Firefox, Safari, and anything after IE9).
Now you learned, How you can use & How to Run JavaScript After DOM is Loaded Without jQuery.
Final Note: Try to Avoid this type of mistake(error) in future!