Read more

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

Ulrich Berkmueller
February 01, 2012Software engineer

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.

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

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.

Posted by Ulrich Berkmueller to makandra dev (2012-02-01 14:37)