Writing to layout properties is free; you can write as much as you want.
It'll only be recalculated on render or when one of its layout properties is read. (scaleHeight)
One common problem is reading, then writing in a loop, which is known as layout thrashing;
The layout is invalidated and recalculated on every single read.
Interleaving reads and writes could mean multiple expensive layout operations per frame.
One fix for DOM thrashing tends to be fairly simple: batch your reads and writes all together. Especially don't change a property then immediately read it.
For example don't append to innerhtml
in a loop INSTEAD build up a string and then write that string to the innerhtml
.
In an mvc or a large framework with many independent modules it can be difficult to ensure modules do not interleave read and writes. Wilson Page's fastdom library can help with this so that reads and writes in a single frame all get done together.
It does this by allowing you to add your read and write callback functions to seperate queues these queues are flushed once per frame. So that it performs all the reads then all of the writes.
Thus giving you an async api to turn interleaved read and writes into queue of layout reads then layout writes.
Sometimes one wants to animate an element growing or sliding in.
Naively one might put a transition on an elements height or left css properties.
Animating properties like these which effect layout will trigger a relayout on every frame.
For example this awful scene here: [slide]
Although it doesn't look like much (and is probably rendering pretty smooth) it is making my fan spin up and get's my phone really hot. With more content or images this would be evident as Jank.
In this particular example I am animating the 'width' property of only a few elements. This is one of the properties which triggers layout. It is being changed and so requires a re-layout every single frame by the css animation.
A good general motto is to calculate all DOM changes first then apply them in a single step.
Changing a single element could have an effect on every single other element on the page.
Every touched element also to be repainted.
Typeface slide
Another reason is the rendering of typefaces. Type is so ubiquitous about the web it is very easily to take it for granted but it is very difficult to render especially when you appreciate that every character needs to be kerned and hinted, every word and paragraph needs to be placed and flowed correctly.
Composite slide
Compositing is great. Transforms such as Rotating or scaling are all done off the main thread.
They are performed on your phone/desktop's graphics chip.
Graphics chips are very good at applying transforms.
The transforms on a single webpage are nothing compared to a modern computer game.