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 UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
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)