cssText and how it can be very very useful

We all know, or at least all of us reading every new coming news on the web development sky, that making your browser reflow and repaint is expensive. Actually it is quite expensive.

What I’m about to say comes under the tag of “very good news” for those how didn’t know what repaint as and what cssText is.

When it comes to the repaint and reflow, which sounds really strange, there are lots and lots of articles what this is, but in breve, just to let you know what is and where’s the bad part of it I’ll describe it again.

Almost every web developer with little or more experience with JavaScript has accessed an element style property with it. This is done like so:

document.getElementById('element_id').style

Now when you try to dynamically place this object somewhere in the browser, you normally just write:

document.getElementById('element_id').style.top = '100px';
document.getElementById('element_id').style.left = '100px';

and that’s when you assume the element is correctly built and his position is absolute. If not – even worse you’ve to make it, again with JavaScript. Which is so sad.

But where is the bad thing that happen in the code above? The bad thing is that the browser should now repaint what you see, once to show you the element with different top position, and again for the left position. This, of course, for the normal browsers occurs very quickly, but don’t ask what price your CPU pays for that!

In the case with only one element moved only once, that’s OK, but what if we move thousands of markers around a map every ten seconds? Than you cannot move your mouse because of the CPU usage.

The simple solution, which in fact is very “software” clear, is to make one class in the CSS definition with both top and left positions predefined:

.my-class { top: 100px; left : 100px;}

and to assign it with:

document.getElementById('element_id').setAttribute('className', 'my-class');

That code makes the browser to reflow only once.

But to make the things clear, let’s ask what if this top and left positions are dynamically calculated? You cannot predefined thousands of thousands of classes, don’t you? And if you can where the hell the optimization is gone?

The right answer is: use cssText.

This is the solution for large scale apps. Just replace the above code with:

document.getElementById('element_id').style.cssText += 'top:100px;left:100px;';

That helps the browser reflow only once and your CPU to breath. Even better that helps other people CPUs to breath, because as you know JavaScript code is executed on the client!

2 thoughts on “cssText and how it can be very very useful

Leave a Reply

Your email address will not be published. Required fields are marked *