How to tell JavaScript to execute a function after an element has been loaded w/out any external library?
Normally I have to bring the <script>
tag after the element itself to work with DOM calls.
The first approach for calling a function on the page load is the use an onload event inside the HTML <body> tag. As you know, the HTML body contains the entire content of the web page, and when all HTML body loads on the web browser, it will call the function from the JavaScript.
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. 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.
Using "defer" readyState = "interactive") and just before "DOMContentLoaded" Event is triggered. If you need to execute the script after all resources (images, scripts) are loaded use "load" event or target one of the document.
The earliest point at which you can run a Javascript function with access to the DOM (without waiting for page load) is by placing a <script> tag right after the opening <body> tag. Scripts inside the <head> will run before this occurs, but there won't be access to the elements on the page.
If you don't want to wait for the full page to load you can also poll for the element's existence:
function myFunc() {
if (document.getElementById('myElement')) {
// do stuff
} else {
setTimeout(myFunc, 15);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With