Wednesday, November 3, 2010

How jQuery .css() performance could be improved.

I've had a need to modify the CSS style of MANY elements on a page (think MASSIVE HTML reports) for much longer than I've known about jQuery. The solution I found, I've only used with IE so far but I'm sure can be implemented with other browsers, is to use proper stylesheet rules to identify groups of elements, then use JS to edit the document.stylesheet itself. The benefit here is that the browser is internally optimized to parse the DOM and apply the styles whereas right now (to my knowledge), jQuery.css() parses all elements matching the selector and then applies the styles.

Obviously this can be a bit more work to setup, but if your pages are as large as mine are, the performance difference is significant. With jQuery.css() I've got updates that take 1.2 seconds compared to .2 seconds when modifying document.stylesheet[].rule[].style.value.

If jQuery.css() were to parse the document.stylesheet.rule collection and look for matching rules, then apply the new style to a rule when a match was found, jQuery.css() could be MUCH faster in many cases.

To take the idea a bit further, when a matching rule isn't found, one could be added to the stylesheet so the browser could then handle style updates, but this approach could get sticky due to rule precedence. The rule (selector) added might be less specific than a different, but applicable one and in that case, would not be applied where the current jQuery.css() approach would apply it since it would add/modify an inline style declaration.

In my search for "how to modify a document stylesheet using jquery" (after wasting much time with a certain arrogant op in #jquery who thought he knew better and should from what I'm told), I did find a great little jQuery plugin that goes a long way toward doing what I seek with jQuery and thus breaking away from browser-specific syntax, but taking advantage of the performance benefits provided by modifying an existing rule. That plugin (not heavily tested on my part, but at the least a great proof-of-concept) can be found at: http://adam.yanalunas.com/blog/archives/100

Instead of using something like:
document.stylesheet[0].rule[0].style.display = 'none';

You'd use something more like (where cssStyleRule is a stylesheet rule object with selector and style):
$(document).CSSSelection(cssStyleRule)
... to add/modify the style of a rule.

BTW, I don't claim to be a jQuery expert and have only been using it lightly for a couple years, but I'm about as new to HTML/JS/CSS as Steve Jobs is to firing the RDF weapon so I think I'm pretty well on track here. If you know different, please enlighten me (without flaming if you want to see your comments posted).

0 comments :

Post a Comment

Followers