如果使用自定义属性选择器而不是使用 jQuery 的长混合类/标签选择器,性能会有所提高吗?
我注意到我们团队中的一些开发人员正在创建长 jQuery 选择器,例如:
'div.someclass > span.someotherclass ...'
我知道,jQuery 将尝试对类和标签使用本机 DOM 方法,但我认为使用精简版的东西是否会更有效:
'[data-gid="my-element-group"]'
而不是那些长的混合类/标签选择器。
自定义属性选择器会比长类/标签选择器更快吗?还是取决于具体情况?为 Javascript 密集的网站选择哪种方法?
PS 我想,如果 HTML 设计者和 Javascript 编码器分开工作,那些长选择器也是危险的 - 设计者可能仅仅通过更改 CSS 类或移动标签来破坏 Javascript 功能。但如果他们看到 ids 和 data-gids,他们可以不理会它们,这应该更安全......但它会牺牲性能吗?
PPS 我不关心无效的 HTML4,因为自定义属性,性能对于我的大多数客户来说更为重要。
I noticed that some of developers in our team are creating long jQuery selectors like:
'div.someclass > span.someotherclass ...'
I know, that jQuery will try to use native DOM methods for classes and tags, but I think if it would be more efficient to use something lite this:
'[data-gid="my-element-group"]'
instead of those long mixed class/tag selectors.
Will custom attribute selectors be faster than long class/tag selectors or it depends on circumstances? Which approach to choose for a Javascript-heavy website?
P.S. I guess, those long selectors are also dangerous if HTML designers and Javascript coders are working separately - designer may break Javascript functionality just by changing CSS classes or moving tags around. But if they see ids and data-gids, they can leave them alone, and that should be much safer... but will it sacrifice performance?
P.P.S. I don't care about invalid HTML4 because of custom attributes, the performance is much more important for most of my clients.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
选择器越长应该越快。这是一个例子。给定以下 HTML:
和以下 jQuery:
这是快速测试的结果:
但是,值得注意的是,在现实世界中,差异很小,您应该使用其中的一个最适合你。
您可以通过使其更具体来使您的
data-*
选择器稍微好一些(性能方面):但另一个快速测试表明(至少在 Chrome 15 中对我来说),较长的选择器仍然获胜。
我认为在不支持
querySelectorAll
的旧浏览器中,差异会更加明显,有利于较长的选择器,它可以使用本机getElementsByTagName
。The longer selectors should be faster. Here's an example. Given the following HTML:
And the following jQuery:
Here's the results from a quick test:
However, it's worth noting that in the real world the difference is going to be minimal and you should use whichever suits you best.
You could make your
data-*
selector slightly better (performance-wise) by making it more specific:But another quick test reveals (for me, in Chrome 15 at least) that the longer selectors still win.
I think in older browsers with no support for
querySelectorAll
, the difference will be even more pronounced in favour of the longer selectors, which can use the nativegetElementsByTagName
.