Notice:
This post is older than 5 years – the content might be outdated.
With the implementation of CSS Typed Object Model (Typed OM), browsers will provide a more convenient way to access and manipulate style values using JavaScript. The Typed
part of the Object Model describes the way the Object Model returns CSS values. Here typed JavaScript Objects are returned that allow handling CSS values in a more performant and less error-prone way.
This article is part of our State of the Web format we publish on a regular basis. Check out our other articles about the newest tech related stuff on the web.
Introduction
The CSS Typed Object Model is part of the Houdini effort and provides an improved CSS Object Model. Instead of using the old CSSOM style
property, Typed OM defines the attributesStyleMap
and styleMap
property to retrieve an element’s or stylesheet’s CSS values. Instead of returning string values, the new APIs offer a typed value as seen in the following example:
With this behavior some great benefits come along. Instead of building up string values e.g. 3 + 'px'
, developers now can easily produce more maintainable code by using typed setter and getter APIs for manipulating CSS values. Eric Bidelman, an engineer at Google, published in his blog post a cube animation that is transformed using the new capabilities. To demonstrate the benefits of the new API, the following sample shows an implementation of the same cube animation using the former CSSOM:
Here you can see that the former implementation is much more complex, as CSSOM requires the developer to split and concatinate string values. Instead of directly incrementing the value, some complex caluculations have to be performed first. Another powerful argument is that the new CSS Typed OM achieves a higher performance on processing CSS values, because the browser doesn’t need to serialize and deserialize string values.
A full implementation of the old and new approach can be found on JSFiddle.
Browser support
Currently, Typed OM only can be used in Chrome version 66+ with only a subset of CSS properties. Whereas Firefox is implementing the new feature Mircrosoft only shows signs of consideration.
With increasing browser support the CSS Typed Object Model will represent a further improvement for the web; dealing with style values never felt so easy.
Further Resources
* Eric Bidelman – Working with the new CSS Typed Object Mode
* Editor’s Draft – CSS Typed OM Level 1
One thought on “CSS Typed Object Model [State of the Web]”