数据属性 css 选择器比类选择器快吗? [英] Are data attribute css selectors faster than class selectors?

查看:22
本文介绍了数据属性 css 选择器比类选择器快吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几个月前这篇文章 指出,实际上可以从网站开发中完全避免类.

A few months ago this article pointed out that classes could actually be avoided all together from website development.

我的问题是,与类选择器相比,数据选择器的效率如何?

My question is, how efficient are the data selectors compared to class selectors?

一个简单的例子是比较使用 data-component='something' 查询元素与使用 class='class1 class2 something anotherClass' 的元素.

A simple example would be to compare querying for elements with data-component='something' versus elements with class='class1 class2 something anotherClass'.

[data-<attr>='<value>'] 选择器将检查整个值与应拆分的类字符串.考虑到这一点,数据属性应该更快.

The [data-<attr>='<value>'] selector will check the value as a whole versus the class string that should be split. With this in mind, data atributes should be faster.

那么,为了细化这个问题,对于 CSS,我们是使用类选择器还是数据选择器更好?而且从javascript的角度来看,jQuery("[data-component='something']")会比jQuery(".something")更高效吗?

So, to refine the question, in the case of CSS, are we better off with class selector or data selector? And from a javascript point of view, will jQuery("[data-component='something']") be more efficient than jQuery(".something")?

推荐答案

我不会称之为决定性的,但看起来类选择器确实更快......我只是把它放在一起快速测试.

I wouldn't call it conclusive, but it does appear class selectors are faster... I just put this together for a quickie test.

http://jsperf.com/data-selector-performance

编辑:

基于 Vlad 和我的 jsperf 测试...如果性能是一个问题(尤其是 IE)...类仍然是要走的路

Based on Vlad's and my jsperf tests... if performance is a concern (especially IE)... classes are still the way to go

这篇关于数据属性 css 选择器比类选择器快吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆