Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS Selectors performance, DOM Parsing

My question is related to DOM parsing getting triggered, i would like to know why it's faster to use a CSS ID selector than a Class selector. When does the DOM tree have to be parsed again, and what tricks and performance enhancements should I use... also, someone told me that if I do something like

var $p = $("p");  
$p.css("color", "blue"); 
$p.text("Text changed!");

instead of

$("p").css("color", "blue");  
$("p").text("Text changed!"); 

improves performance, is this true for all browsers? Also how do I know if my DOM tree has been re-parsed?

like image 581
Astronaut Avatar asked Apr 17 '12 13:04

Astronaut


People also ask

Which CSS selector is faster?

popupbutton is the fastest.

Are CSS selectors slow?

If you work in front-end coding you've probably heard this one: Using classes makes the render stage of pages load faster than selectors and combinators. Selectors are “Slow”, “inefficient”, “require too much DOM Traversal”, “lack code clarity”, etc, etc.

Which CSS selector has the highest precedence in execution?

Values defined as Important will have the highest priority. Inline CSS has a higher priority than embedded and external CSS. So the final order is: Value defined as Important > Inline >id nesting > id > class nesting > class > tag nesting > tag.


1 Answers

Well, an #id selector is faster than class selectors because: (a) there can only be one element with a given id value; (b) browsers can hold a map id -> element, so the #id selector can work as quick as a single map lookup.

Next, the first option suggested above is definitely faster, as it avoids the second lookup, thereby reducing the total selector-based lookup time by a factor of 2.

Last, you can use Chrome Developer Tools' Selector Profiler (in the Profiles panel) to profile the time it takes a browser to process selectors in your page (match + apply styles to the matching elements.)

like image 164
Alexander Pavlov Avatar answered Sep 21 '22 12:09

Alexander Pavlov