jquery选择器与css3选择器的性能 [英] Performance of jquery selectors vs css3 selectors

查看:197
本文介绍了jquery选择器与css3选择器的性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对css3使用选择器(或一般的简单css选择器)相当新,我很好奇这些css选择器与jquery或javascript选择器的性能比较。



说你有这样的:



css版本

  someID> div:nth-​​child(2n){some css ....} 

  $(#someID)。children(:nth-​​child(even) ....}); 

使用css选择器通常更快,或者使用jQuery选择器来调整css涉及一个元素或一组元素?主要是当集合变得相当大。



谢谢!

解决方案

jQuery的选择器引擎与CSS大体上具有相同的语法,可以有效地扩展选择器标准。这意味着您可以传递最有效的CSS选择器(使用一些例外)到



jQuery通过将选择器API直接传递给 document,为现代浏览器优化有效的CSS选择器.querySelectorAll()。这意味着你的jQuery选择器将与等效的CSS选择器几乎相同的性能,只有开销是 $()。css()和选择器API调用。 p>

对于不支持选择器API的浏览器,很明显,jQuery会很慢,因为它必须自己做所有的繁重工作。更重要的是,对于我链接到上面的异常以及浏览器不支持的任何其他CSS选择器,它将会失败。



但是, ,jQuery 将会更慢,因为浏览器必须运行脚本并在获得应用和计算你的样式之前对其进行评估。



<毕竟,这一切,老实说,即使你有数百个项目,也不是很多 - 有机会是浏览器需要更长的时间来获取标记比渲染样式。如果你需要做样式,而CSS支持它,为什么不使用CSS?这就是为什么语言是创建在第一位。


I am fairly new to css3 using selectors (or simple css selectors in general) and am curious about the performance comparison of these css selectors vs jquery or javascript selectors?

Say you have something like this:

css version

#someID > div:nth-child(2n) { some css .... }

jquery version (edit)

$("#someID").children(":nth-child(even)").css({ some css ....});

Is it often faster to use the css selectors whenever you can, or use jquery selectors to adjust the css involved with an element or set of elements? Mainly when the set gets rather large. I would assume there wouldn't be much performance difference with only a handful of items?

Thanks!

解决方案

jQuery's selector engine shares most of the same syntax as CSS, effectively extending the selector standard. This means you can pass most valid CSS selectors (with some exceptions) to jQuery and it'll handle them just fine.

jQuery optimizes valid CSS selectors for modern browsers that support the selectors API by passing them directly to document.querySelectorAll(). This means your jQuery selector will have almost equal performance with the equivalent CSS selector, with the only overhead being the $().css() and the selectors API calls.

For browsers that don't support the selectors API, well, it's pretty obvious that jQuery will be really slow as it has to do all the heavy lifting on its own. More importantly, it will simply fail on the exceptions that I link to above as well as any other CSS selectors a browser doesn't support.

However, with all that said, jQuery will invariably be slower, as the browser has to run through a script and evaluate it before getting a chance to apply and compute your styles.

And after all this, honestly, it's not much even if you had hundreds of items — chances are the browser is going to take longer to fetch the markup than to render the styles. If you need to do styling, and CSS supports it, why not use CSS? That's why the language was created in the first place.

这篇关于jquery选择器与css3选择器的性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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