Why your javascripts should be executed after the dom has been loaded

Posted Over 12 years ago. Visible to the public.

Most of the JavaScript snippets have code that manipulates the DOM. For that reason dom manipulating javascript code should have been executed after the DOM has loaded completely. That means when the browser has finished HTML parsing and built the DOM tree. At that time, you can manipualte the DOM although not all resources (like images) are fully loaded.

The following snippets show how you can do this with plain JavaScript, jquery Show archive.org snapshot or prototype Show archive.org snapshot ( dom ready event binding in other frameworks Show archive.org snapshot ).

Plain JavaScript
document.addEventListener("DOMContentLoaded", function() {
var elements = document.querySelectorAll('.divs_to_hide');
}, false);

jQuery
$(function() {
$('.div_to_hide').hide();
});

Prototype
document.observe("dom:loaded", function() {
$$('.divs_to_hide').invoke('hide');
});

What happens if you don't encapsulate your dom manipulating code into a DOM-ready callback?

If you are lucky, your code works as expected. But generally it could be the case that your JavaScript snippet is executed before the DOM tree has been loaded. That means that for example a DOM-manipulation will fail even though the element(s) you would like to manipulate exist(s) in the delivered HTML.

So you should always encapsulate DOM-manipulating javascript code in a DOM-loaded callback.

By the way: Encapsulating your code with closures as used in the examples above would have the advantage not to pollute the global scope and to reduce unexpected side-effects.

Ulrich Berkmueller
Last edit
About 12 years ago
License
Source code in this card is licensed under the MIT License.
Posted by Ulrich Berkmueller to makandra dev (2012-02-01 13:37)