Using data-* attributes in JavaScript and CSS

When HTML5 got defined one of the things that was planned for was extensibility in terms of data that should be in the HTML, but not visible. The data-* attributes allow us to store extra information on HTML elements without needing to use a non-semantic element or pollute the class name. In essence this is what we did with custom attributes before.

These data attributes can be used in many ways, some are a bad idea but others are a good plan. The rule of thumb is that content that should be visible and accessible should not be stored in them. The reason is that assistive technology is not likely to be able to access them and search crawlers don’t index them either.

The syntax is dead easy. Say you have an article and you want to store some extra information that doesn’t have any visual representation. Just use data attributes for that:

Data attributes can also be stored to contain information that is constantly changing, like scores in a game. Using the CSS selectors and JavaScript access here this allows you to build some nifty effects without having to write your own display routines. See the following screencast for an example using generated content and CSS transitions:

Issues with data-attributes

Sadly enough it seems there is nothing that is so simple and useful that doesn’t come with a price. In this case the main issues to consider are that Internet Explorer does not support the dataset but you’d need to read them out with getAttribute() instead. The other issue is that the performance of reading data-attributes compared to storing this data in a JS data warehouse is bad. Using dataset is even slower than reading the data out with getAttribute().

That said, though, for content that is not to be shown they are a great solution and maybe we can get them into the next IE soon.

“That’s true. I am waiting for the prime time to using it in production. Thanks for the article.”

I am using in production there — http://professionali.ru/. It’s also works in IE8, but has issues not only with dataset, but with that what IE does not repaint when data-* property is changed, so, I used hack to force repaint in IE.

Why is dataset so slow? Why is it even slower than get/setAttribute? It got its own API, it should be faster or at least as fast as get/setAttribute. The way it is currently implemented will not make anybody use the special API …

On a related note: Is web content something Snappy is concerned about?