[JavaScript] load / DOMContentLoaded events

When working with JavaScript, you might wonder where you need to initialize your code (especially with DOM elements). There are a couple of ways to do it.

1. Initializing DOM elements

Suppose you want to set the random initial value (from 1 to 10) to the textbox.

<div>
  Random Value =
  <input id="randVal" type="text" />
</div>

You have a function to get the value.

var textbox = document.getElementById("randVal");
textbox.value = Math.floor((Math.random() * 10) + 1);

Now where do you place this code to successfully initialize the textbox?

 

2. <head>

The most common place to put the code is in the <head> section.

<head>
  <script>
  var textbox = document.getElementById("randVal");
  textbox.value = Math.floor((Math.random() * 10) + 1);
  </script>
</head>

If you open this page in the browser, you will get an error, somethink like “Unable to set value of the property ‘value’: object is null or undefined“.

When the document is parsed, browsers execute the JavaScript code as soon as the code is encountered. The code is executed even before the <input> element is loaded.

 

3. At the end of the Document

Now, you can make use of the feature mentioned in the previous section. You can place the <script> tags at the end of the document. When the code is executed, all elements are already loaded.

<body>
  <div>
    Random Value =
    <input id="randVal" type="text" />
  </div>
  <script>
  var textbox = document.getElementById("randVal");
  textbox.value = Math.floor((Math.random() * 10) + 1);
  </script>
</body>

 

4. load Event

Even though you can put the code at the end of the document, it is not a good practice. What if you want  to move the code to the separate file?

The better approach is to use the events. Let’s start with the familiar “load” event.

window.onload = function () {
  var textbox = document.getElementById("randVal");
  textbox.value = Math.floor((Math.random() * 10) + 1);
};

You can place this code at any place.

 

5. DOMContentLoaded

The problem of the “load” event is that the event is fired when all supporting files (styles and images) are completely downloaded and loaded. This behavior might be a problematic when the page includes many big images files.

The “DOMContentLoaded” event is fired when the document has been completely loaded and parsed but without waiting for stylesheets, images, and subframes to finish loading.

document.addEventListener("DOMContentLoaded", function () {
  var textbox = document.getElementById("randVal");
  textbox.value = Math.floor((Math.random() * 10) + 1);
});

This event is HTML5 feature and supported in all major browsers (IE 9+).

 

6. jQuery ready()

jQuery provides the “ready()” function to execute when the DOM is fully loaded. It is similar to the “DOMContentLoaded” event. It is fired before supporting files are all ready.

Let’s test previous 2 events and the “ready()” function.

$(document).ready(function () {
  alert("ready");
});

window.onload = function () {
  alert("load");
};

document.addEventListener("DOMContentLoaded", function () {
  alert("DOMContentLoaded");
});

What will happen? Which order do you think the events will trigger?

ready” -> “DOMContentLoaded” -> “load

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s