Forum Moderators: not2easy

Message Too Old, No Replies

Using data-attribute in place of class names

         

csdude55

6:32 am on Mar 5, 2019 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I feel like we discussed this a year or two ago, but I couldn't find it. And whatever was said is probably outdated now, anyway. I haven't been able to code in about 6 months and I'm finally getting back in to the groove...

Assuming that I'm strictly using the class name for styling, is there any particular reason to NOT use a data-attribute in place of a class name?

Example:

<style>
.flex { display: flex }
</style>

<div class="flex">
blah blah blah
</div>


Or:

<style>
[data-flex] { display: flex }
</style>

<div data-flex>
blah blah blah
</div>


The data-attribute seems to be well supported:

[caniuse.com...]

The only real advantage would be saving a few bytes of bandwidth, but bytes DO add up. I obviously wouldn't use it in cases where there would have been multiple classes or it would take more space, but for containers that would only ever have the one class it's marginally smaller.

If there's no disadvantage then, while I'm rebuilding, is there any reason to not use it in place of a class?

robzilla

10:45 am on Mar 5, 2019 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I would expect an attribute selector to be more expensive than a class selector, but these days (with modern browsers at least) the difference may not be worth fussing over.

You obviously wouldn't be using the data attribute for its intended purpose, the class attribute is more widely supported, and I don't see this saving you much bandwidth after gzip.

So I don't really see the point of this. There are probably better ways to spend your time.

csdude55

7:57 pm on Mar 5, 2019 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I still have a small but significant number of dial-up users (think rural areas), so I'm always counting my pennies on load time :-) But if the processing time is longer then it might negate the smaller file size, so that's something to think about.

This test was in 2014, but kind of interesting and relevant to the topic:

[ecss.io...]

So the speeds seem virtually identical, but you're right that it might be more trouble than it's worth at this point. I could foresee saving up to 1kb on an infinite scroll page, but even on dial-up that would be negligible.

tangor

2:26 am on Mar 6, 2019 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



As always K.I.S.S. rules, but sometimes a fine tune can help. However these days 1k BYTES is chump change.... even in rural areas. (USA)

Why? If they can get the web at all they are already "fast enough" because the web is code heavy and (sigh) image and audio and video oh my!