DEV Community

Cover image for A simple, practical tip to improve performance in the front-end.
Jack Shen
Jack Shen

Posted on

A simple, practical tip to improve performance in the front-end.

W3C maintains a list of JavaScript best practices, one of which is an imperative to "keep DOM access to a minimum". That's all well and good, but what does it really mean in more practical terms? Let's explore this with a simple example.

Let's say for stylistic purposes, I would like my website to have an element I can drag around inside the window. The script might look something like this:

const draggable = document.getElementById("draggable");

let isDragging = false;
let offsets = {};

// Start drag
draggable.addEventListener("mousedown", () => {
  isDragging = true;
  /* Get offset between mouse and element position here */
});

// Drag
document.addEventListener("mousemove", () => {
  if (!isDragging) return;
  /* Update top and left styles here */
});

// Stop drag
document.addEventListener("mouseup", () => {
  if (isDragging) isDragging = false;
});

In order for the element to be draggable around and over other elements in the same window, it would need these CSS style properties:

<div
  id="draggable"
  style="display: absolute; left: 300px; top: 500px"
></div>

The script would work by updating the left and top properties whenever the mousemove event is fired.

How might you get the current left and top property values, in order to perform the necessary calculations? You might be tempted to directly access them through the element's styling, with draggable.style.left or getComputedStyles(draggable).top.

This is a trick question. You should avoid accessing the DOM at all.

Here's a better approach:

const draggableCoords = { left: 300, top: 500 };
const draggable = document.getElementById("draggable");

draggable.style.left = `${draggableCoords.left}px`;
draggable.style.top = `${draggableCoords.top}px`;

// The rest of the code

What I did here was set the source of truth for draggable's left and top styles inside the script. By making JavaScript the foundation of my application, the HTML is now dependent on the script, and not the other way around. This nicely avoids having to access the DOM altogether.

The benefit of this approach is immediately obvious. While the performance benefits for my example aren't significant, it is clear how the computational advantage would be magnified in a complex, production-scale project.

Top comments (0)