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?
popupbutton is the fastest.
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.
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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With