JavaScript

Always avoid the DOM

The beauty of nodejs is that you don't have to work with the DOM. On the browser, that's where JavaScript power lies. The only problem is it is terribly slows. DOM access are the most expensive transactions. It is my turn off when it comes to many framework. However, some do make the effort to only read the DOM entirely at page load, so they never have to parse or read it again.

There are some transactions that are easier to do if you check the properties of a DOM element directly. But it is much more efficient to store the states in a variable instead. Let's think about a button that toggles a div.

The simple way of dealing with it will be to just check the css display property and do the opposite.

<button id="button">Toggle</button>
<div id="toggleme">Look at me maw!</button>

<script>
var btn = document.getElementById("button");
var div = document.getElementById("toggleme");

btn.onclick = function () {
    if (div.style.display === "none"){
        div.style.display = "block";
    }else {
        div.style.display = "none";
    }
};
</script>

In this example, we always get the state from the div. We check the value of display then we set it. This means, we access the DOM element twice for every click. Because we are greedy, we can limit it to one DOM access.

All we have to do is store the state in a variable.

var isVisible = div.style.display !== "none";

That's it. Now isVisible is a boolean. We can simply check it before we set the current state of the div.

var isVisible = div.style.display !== "none";
btn.onclick = function(){
    if (isVisible){
        div.style.display = "none";
        isVisible = false;
    }else {
        div.style.display = "block";
        isVisible = true;
    }
};

There you go. Well I know what you are saying. The performance gains for this particular case are close to nil. That is true. But the same method can be used for more complex code. If you are parsing the DOM every time you click, you can convert your code to something like this instead. Make sure you only parse the DOM once and save all the values you need.


Comments

There are no comments added yet.

Let's hear your thoughts

For my eyes only