3

“The world is its own best model”

is a catchphrase originated by Rodney Brooks, in describing behavior-based robotics. This is the idea that in order to be versatile and robust, robot behavior should be designed out of simple and direct responses to the world, as opposed to having a robot store and act upon an accurate representation of its environment in its memory bank. The problem with the latter approach is that it a) is really programmatically costly and b) ends up being really brittle (the robot fails to respond dynamically when faced with some new thing that it can’t analyze well).

I think a similar motto can hold in web design:

“The DOM* is its own best model”
*/stylesheet

As I’ve built more websites, I lean more and more towards not storing data and instructions in JavaScript unless absolutely necessary, because that requires you to account for every scenario where the values or rules change, which is on the one hand a strain for the programmer trying to anticipate every condition, and on the other it’s a strain for the computer doing all sorts of checks in JavaScript rather than at a lower level. It’s usually possible and much more efficient to store data directly in the HTML/CSS. Some examples of this I’ve found:

  • If you have a lot of elements and you need to record some piece of information about each one of them, you could make an array of items with some way to match an item to an element, but storing it using data attributes is more straightforward and less error-prone in most cases.
  • If you need to make a calculation based on an element’s dimensions in order to set the value of something else, CSS’ calc (usually in combination with CSS variables) is going to be more reliable and less costly in most cases, particularly if it’s something that would otherwise need to be updated on resize, and which instead is handled dynamically by CSS’ variable units (%, vh, vw, etc).
  • If you need to update a lot of styling on an element dynamically, don’t modify styles directly in Javascript. Create a CSS class with all the relevant changes, and apply the class using JS as needed. Way more efficient.
  • In tandem with the above bullet, CSS transitions and animations are the best way of doing simple animations 90% of the time.
the DOM as its own best model