Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run JavaScript function when the DOM is "ready"?

Tags:

javascript

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?

like image 317
miahelf Avatar asked Nov 03 '11 09:11

miahelf


People also ask

How do I run a function after the page is loaded?

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.

Can I run JavaScript before the whole page is loaded?

But yes, it is an option.

How do I run a script after DOM loaded?

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.


1 Answers

<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.

like image 162
Shadow2531 Avatar answered Sep 18 '22 01:09

Shadow2531