Run JavaScript function when the DOM is "ready"?

The easiest solution is using jQuery and its $(document).ready(function() { .... }); function. Instead of .... you put your own code.

Note that it basically does the same thing @Shadow2531 suggested, but also works in old browsers not supporting that event.


The DOM is usually ready before onLoad runs. onLoad only runs after everything loads - external scripts, images, stylesheets, etc.

But the DOM, i.e. the HTML structure is ready before that. If you run the code at the bottom of the page (or after the parts of the page the script works with) that will work fine as well.


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


In 2015 you have two options with modern browsers:

document.onload

  • this fires when the document is loaded, but other resources (most notably images) have not necessarily finished loading.

window.onload

  • this fires when the document is loaded, AND all other resources (again, most notably images) are loaded.

Both of the above events would be better utilized with window.addEventListener() of course, as multiple listeners would be allowed.

Tags:

Javascript