0

I'm doing a lot of

 element.css {
     style1: val1
     style2: val2
     ...
 }

using jQuery, and right now it's a performance bottleneck for me. Looking at jQuery's implementation, it seems to be setting each style individually, resulting in multiple modifications of the style attribute.

Presumably in this case, we only need to modify the style attribute once. However, I'm a little hesitant to re-implement .css. Has anyone done this already? If I do decide to reimplement it, are there going to be gotchas to be aware of?

2
  • 3
    how about adding/removing classes instead? That would also make the js-code much cleaner. Commented Jan 29, 2014 at 0:33
  • I'm generating the styles on the fly, otherwise that would be my first choice Commented Jan 29, 2014 at 0:36

2 Answers 2

1

The biggest performance hit with setting styles comes from trashing the layout. That happens when you change an attribute that influences the layout (ex: width) and then immediately ask for information about the layout. If you don't do that (for example by batching the changes together), then setting the style one property at a time versus the whole style text at once is pretty much the same, as the rendering engine is pretty smart about that.

So instead of doing:

$('.myItem').each(
  $(this).css('width', $(this).css('width') + 10);
);

change to:

var widths = [];

$('.myItem').each(
  widths.push($(this).css('width'));
);

$('.myItem').each(
  $(this).css(widths.shift() + 10));
);
Sign up to request clarification or add additional context in comments.

1 Comment

I tried testing .css vs blazemonger's solution, and the improvement seems pretty marginal, so I think you're on target...
0

Append a single string to the style attribute, then -- later styles will automatically override earlier ones.

$(el).attr('style',$(el).attr('style')+newStyleString);

However, if you can't perceive a performance hit in your web page, I wouldn't worry about it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.