Performance of jquery selectors vs css3 selectors - 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.

Pure CSS will always be faster since it's done within the browser and optimized!
The downside is that some selectors might not be supported by the browser you're on. See http://caniuse.com/#feat=css-sel3

For me if I use jquery means that I want to put some effect on it, say like
$("#someID:nth-child(even)").css({ some css ....}).fadeIn('slow');
Apart from that you better use CSS itself, but we are barely to see the difference of it anyway, at least for a small scope system.
I've found this web that compare selector capability from different javascript framework and jquery does it quite well.
javascript framework selector test

Related

what is better angular directive or css selector?

I'm learning angular and I'm testing the directive ngClass.
With ngClass I can do something like that:
<li ng-repeat="language in languages" ng-class="{line:$even}">{{language}}</li>
But I can also do this with the css selectors:
li:nth-child(even) {
// some css code here
}
What is better?
First of all two cases are not equivalent. But if what you are looking is a way to style even/odd elements, then without any doubt: you should use CSS to do CSS job, not javascript. Using javascript to add class names is possible but if it's not important to have actual class names on elements then sticking to :nth-child approach is preferred in this case.
Two main benefits of pure CSS way:
Avoiding additional watchers Angular would have to set for data binding.
Performance and cleaner HTML code.
I see ng-class as a visual port of some property of the model. It is not intended just for styling, but can offer it.
IMO it is always best to do as much as you can using standards, that way you're less dependent on others.
There are plenty other reasons why using CSS is better, like: performance, less error prone, less dependent etc.

Are nested ids okay if necessary -- performance hit or other?

I'm using a jQuery-based framework (Kendo UI) which comes with its set of highly selective css rules.
In order to avoid the headache of my css rules clashing (and also to avoid using !important all over the place), I've nested everything in a body id -- e.g., #body-id .my-class.
However, is there a performance hit or other issue in using:
#body-id #my-other-id?
Every resource I find says, "it's pointless and makes no sense semantically." I agree, however, as I'm using the Less CSS framework, my entire CSS stylesheet will be wrapped in #body-id (for simplicity sake). Thus, it would eventually compile to #body-id #my-other-id (I'm assuming).
The jQuery selector speed is not very important, because there are other more narrow bottlenecks in your browsers JavaScript implementation.
Only if you have many, many jQuery operations like this to perform, the speed performance will be an issue
But by the way jQuery analyzes the selector (from right to left) an id with child selectors does not profit from javascript getElementById speed.
So it's more or less not important. But it may be not good style.
Check, if your CSS code is modular!
Edit
Here is a 'official' resource on performance and else
http://learn.jquery.com/performance/optimize-selectors/

CSS3 Selectors in IE8?

Alright, so I recently found this script called "Selectivizr" and I was really excited, but I plugged it into my project, set it up just as it said, and it didn't work.
So, what I am looking for is any sort of JavaScript library/script that will allow me to use CSS3 selectors (especially :checked) in IE8.
Selectivizr seems broken, and hasn't been updated in over a year. Has anybody else had luck with it?
Does anybody know of any other scripts that will allow for use of CSS3 selectors in IE8?
Not looking for CSS3 stylings like border radius, shadows, etc. Just looking for the selectors, like :before, :after, :checked, etc...
Dean Edward's IE9.js is pretty solid, though I have heard of some incompatibility problems when using other libraries as well. Never experienced them myself, but haven't used the library too often in the wild for a long time. Plug it and play, and if it doesn't break then you're all set.
Link: http://code.google.com/p/ie7-js/
Demos: http://ie7-js.googlecode.com/svn/test/index.html
With jQuery code, you can use these few lines to toggle a class on all your checkboxes (or on it's container) any time it's checked or unchecked. This then lets you use regular CSS code in all browsers.
$("input[type='checkbox']").click(function() {
$(this).parent().toggleClass("checked", this.checked);
});​
Working example here: http://jsfiddle.net/jfriend00/7jA5r/.
If you dynamically create checkboxes, then you could use the dynamic form of .on() to make sure to catch them.
I would personally rather use a solution with a few lines of code like this than use a heavy library that tries to add CSS style file capabilities. If you were going to use that, make sure you understand what's really going on under the covers before you adopt it.
If you just wanted a selector libraryby itself, the Sizzle selector library works across a wide variety of browsers including all the way back to IE6. It will adapt to the capabilities of the host browser, using as many built-in capabilities as are present and using it's own code when the host browser does not support an explicit capability.
You can use just the selector library itself from here or it is also the selector library inside of jQuery.
It's extremely simple to use. You just do something like this:
var items = Sizzle(":checked");
and you will have an array of DOM elements that match the selector.

CSS Specificity Filter

This is a long shot, but is there a tool available that optimizes CSS selectors by removing unneeded specificity?
I find that when I write CSS, I deliberately make my selectors more specific than necessary to avoid conflicts and for quasi-documentation.
It would be great if there were a tool that could analyze a given group of rules, determine their "uniqueness" in terms of overlap with other rules, and then strip away any unnecessary specificity.
I can't even begin to imagine how a tool developer would approach all of the scenarios this would require, but I've been blown away by others' ingenuities in this area before and figured it was worth asking.
Update:
I've added a bounty to this question, and the more I think about it, the more I realize how valuable a CSS Specificity Filter would be.
For example, when working with Nested Rules/Selectors in Sass and LESS, excessive nesting is a common and well-known antipattern that can easily lead to overly specific selectors.
There's a good illustration of this in the excellent TutsPlus course Maintainable CSS with Sass and Compass:
body {
div.container {
p {
a {
color: purple;
}
}
}
}
Sass will follow these nesting instructions and produce the following CSS output, raising no objection to any unneeded specificity:
body div.container p a {
color: purple;
}
If a Specificity Filter did/does exist, however, it would create potential benefits for CSS developers:
You could organize your stylesheets as a 1:1 mapping of the DOM, similar to what you see when you examine style rules in Firebug and Chrome Dev Tools. A smart editor/IDE could auto-populate styles for DOM elements with shared styles/classes. That redundancy would then, of course, be filtered out by the Specificity Filter/Optimizer.
Stylesheets could have their structure pre-populated by a tool that scans the DOM and translates it to CSS selectors/rules. This means a developer would only need to update the HTML; the CSS "tree" would be kept in sync to reflect the current state of the DOM. A smart editor would let you jump to the CSS definition for an element/class for styling -- or even make its style rules visible in a separate panel.
In a way, this almost seems like a step backward - like a feature you'd find in Dreamweaver or WebAssist to help newbs learn CSS. But the basic idea of a CSS selector optimization tool seems like a no brainer, and the type of workflow automation I've described would be the logical next step -- and the catalyst would be the Specificity Filter.
I looked into some of the better-known CSS editors and web IDEs, but haven't found anything offering this type of functionality beyond targeting a single element and generating a selector for it.
Update 2: CSS Selector Performance
In response to Spliff's comment, here are two great articles on CSS selector performance:
Performance Impact of CSS Selectors by Steve Souders
Efficiently Rendering CSS by Chris Coyier
Both agree that micro-optimizing CSS isn't worth the effort, but that over-qualified descendant selectors are "an efficiency disaster." I haven't benchmarked yet myself, but suspect that the kind of "DOM Mapping" approach I'm suggesting would cause a performance hit without an optimization step, either manual or automated.
Related Questions, Links, and Tools:
Points in CSS Specificity
Tool to See CSS Specificity
Tool for Cleaning Up CSS
Order by CSS Specificity
Top 5 Mistakes of Massive CSS
Google: Efficient CSS Selectors
Procssor
Clean CSS
CSS Tidy
You could attempt to take a different approach, try to write your selectors as small (low specificity) as possible. and only make them more specific when needed.
With that way of working you don't need a tool.
Just going to throw this out there-- it doesn't 'answer' your question,but it's a tool I like to spread the word about for people who do a lot of css programming: Firebug.
If you're not familiar with it, it's a tool for web browsers. You pull up your page once it's installed, right click and select 'Inspect Element.' It will show you all css affecting different elements on your page, and is useful for creating clean, precise css code. Also it makes it easier to see instant updates on what your page would look like with slight modifications. It will inform you of useless css code that's being overridden by other css code.
ALSO! Firebug now is available for almost all browsers. Not just Firefox. Personally, I'm partial to using it in Chrome.
We really can't do without specificity because it is the only thing that saves you when you have two or more rules colliding. Specificity brings sanity to the whole jumbled CSS rule, so it is more of a blessing than curse. Some of the stuff you talked about, like the CSS selector, can be done using Firefox/Firebug. I'm more disturbed by browser compatibility.
Actually there's a way you can do this using HTML5 and CSS3. The standard technique is to specify elements using the HTML 5 attribute "data-" and then do CSS selection for this attribute. This isn't the purpose of the attributes, but you can customly specify some elements that you can use to even switch the theme of a site.
So, for example, you can end up creating your specificity filters manually in CSS, by specifying
<b data-specificity=2>test</b>
where data-specificity only matches to parents above.
UPDATE:
Alright, so for example, let's say you have a paragraph class, but you want to specify which parent, or how many parents the paragraph can inherit properties from. You would use rules for each potential parent that can be inherited from:
p[data-specificity="1"]{
color:red;
font-family:verdana;
text-decoration:underline;
}
p[data-specificity="2"]{
color:black;
font-family:arial;
}
div.container > *[data-specificity="2"] {
font-family:impact;
color:blue;
text-decoration:underline;
}
So these rules mean that any p tag which is a direct child of the div container and has specificity 2, is allowed to inherit properties from the div container. The blue color of the div gets inherited by the p with data-specificity 2.
Here's a JSFiddle where you can see this!
The idea is that like this, using HTML5, you can control exactly which elements are allowed to inherit which properties. It's a lot of extra code to write (for both child and parent elements) but you can use this to get rid of some unnecessary specificity
I've never actually seen anyone use this method in practice, I pretty much just cooked it up for you, but I think it could be very useful, what do you think ?

CSS selector performance?

Is there a performance difference between these 2 selectors assuming they match the same # of elements (a single form)?
#master .body form {}
#master form {}
I've heard that CSS selectors can make an appreciable speed difference for page rendering. I was also curious if this applies mostly to page load times or also for scenarios where you add a class to an element via JavaScript and how fast the browser can render that visual change.
interesting stuff in there:
http://calendar.perfplanet.com/2011/css-selector-performance-has-changed-for-the-better/, http://www.stevesouders.com/blog/2009/03/10/performance-impact-of-css-selectors/
Google has a plugin for Firebug/Developer Tools that analyzes your page's speed. One of its tabs is for CSS selectors. You just have to run it and it will tell you which one is better.
From what I know, by the way, the first is slower. The less elements you need to select, the better.

Resources