[Preference] How to avoid Forced Synchronous Layout or FSL to improve site preference

When tigger site updates the layout, it always follow this order:

 

Javascript trigger style changes, then layout changes then broswer do the paint and composite

All those five steps should be finished in 60fps, or 16ms. Then users will have a smooth and good user experience.

 

For "layout", "style" and "composite", please check this site: https://csstriggers.com/

From the site, you can see that, 'transform' and 'opacity' has good preference, because they only trigger "composite", save lot of works for the broswer.

 

 

Also you can see that the method for "left", "right", they triggers all "layout", "paint", "composite"

 

Now let see "style" and "layout".

In general, "style" should happen before "layout", otherwise, broswer need to rerender "layout"->"style"->"layout" all over again, which is a waste for the perfermence.

To see which opreation will cause "layout" recalcuation, please checkout http://gent.ilcore.com/2011/03/how-not-to-trigger-layout-in-webkit.html, basiclly, be careful with those:

clientHeight, clientLeft, clientTop, clientWidth, focus(), getBoundingClientRect(), getClientRects(), innerText, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerText, scrollByLines(), scrollByPages(), scrollHeight, scrollIntoView(), scrollIntoViewIfNeeded(), scrollLeft, scrollTop, scrollWidth

 

Let's see an example how bad it can affect our site prefermence. Example site

In this bad example, you can see taht Recalculation for "style" -> "layout" -> "style" .... "layout", it repeat number of times.

 

 

 Let's see the code causes this:

        function firstRun() {
          divs.forEach(function(elem, index, arr) {
            if (window.scrollY < 200) {
              elem.style.opacity = 0.5;
            }
          })
        }

As you can see in a forEach loop, every time you call "scollY" will cause a layout update, then we call "style.opacity" to trigger style update, but after style updated, layout will be updated again because the order, remember?

 

Let's see how to fix the problem:

        function thirdRun() {
          var newWidth = container.offsetWidth;
          divs.forEach(function(elem, index, arr) {
            elem.style.width = newWidth + "px";
          })
        }

We can simply move 'layout' update code out of forEach loop. Now the timeline looks much better!

 

 

posted @   Zhentiw  阅读(381)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2016-04-06 [Angular 2] Property Binding
2016-04-06 [Angular 2] Interpolation: check object exists
点击右上角即可分享
微信分享提示