[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!
最新文章
- 双日历时间段选择控件—daterangepicker(汉化版)
- python查找空格和中文
- 状态压缩DP
- python 判断操作系统类型
- inline-block元素的一些坑
- Sublime Text 2 插件
- BFC / hasLayout
- (转)iOS项目的目录结构和开发流程
- Struts文件上传
- 网站开发进阶(四十四)input type=";submit"; 和";button";的区别
- js+jquery创建元素
- [原创]..\OBJ\gpio.axf: error: L6002U: Could not open file ..\obj\gpio.o: No such file
- SpringCloud(8)---zuul权限校验、接口限流
- DotNetCore深入了解之二HttpContext类
- java-Collection集合、List集合、Vector集合和迭代器Iterator、ListIterator的使用
- gdb 使用
- 20155219 2016-2017-2 《Java程序设计》第10周学习总结
- UT源码_105032014033
- Lucene4.x创建索引与3.x的一些不同
- JQueryEasyUI easyui-combobox 单击文本区域显示下拉菜单