I'm using a JavaScript upload script that says to run the initialize function as soon as the DOM is ready. I currently have it working just fine with either a call to the function with body.onload
or directly after the function is defined. The function builds some HTML in a placeholder div that acts as the file uploader tool.
My question is what is the best practice here? Since it works for now, why would the instructions say to run the init function as soon as the DOM is ready? Should I be adding a <script> tag directly after the placeholder DIV for example?
Method 1: Using onload method: The body of a webpage contains the actual content that is to be displayed. The onload event occurs whenever the element has finished loading. This can be used with the body element to execute a script after the webpage has completely loaded.
But yes, it is an option.
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.
<script> window.addEventListener("DOMContentLoaded", function() { // do stuff }, false); </script>
You do that so you know all the parsed elements are available in the DOM etc.
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