减少重绘和回流的方法_最小化回流并提高性能的10种方法

减少重绘和回流的方法

Despite web pages reaching 2MB performance remains a hot topic. The slicker your application, the better the user experience and the higher the conversion rate!

尽管网页达到2MB的性能仍然是一个热门话题。 应用程序的流畅性,更好的用户体验和更高的转换率!

That said, I’m guilty of adding superficial CSS3 animations or manipulating multiple DOM elements without considering the consequences. Two terms are used in the browser world when visual affects are applied:

就是说,我有罪,只是添加了表面上CSS3动画或操纵多个DOM元素而没有考虑后果。 应用视觉效果时,在浏览器世界中使用两个术语:

Repaints A repaint occurs when changes are made to elements that affect visibility but not the layout. For example, opacity, background-color, visibility, and outline. Repaints are expensive because the browser must check the visibility of all other nodes in the DOM — one or more may have become visible beneath the changed element.

重新绘制当对影响可见性但不影响布局的元素进行更改时,就会发生重新绘制。 例如, opacitybackground-colorvisibilityoutline 。 重新绘制很昂贵,因为浏览器必须检查DOM中所有其他节点的可见性-在已更改的元素下可能已经可见一个或多个。

Reflows Reflows have a bigger impact. This refers to the re-calculation of positions and dimensions of all elements, which leads to re-rendering part or all of the document. Changing a single element can affect all children, ancestors, and siblings.

回流回流具有更大的影响。 这是指重新计算所有元素的位置和尺寸,从而导致重新呈现部分或全部文档。 更改单个元素会影响所有的孩子,祖先和兄弟姐妹。

Both are browser-blocking; neither the user or your application can perform other tasks during the time that a repaint or reflow occurring. In extreme cases, a CSS effect could lead to slower JavaScript execution. This is one of the reasons you encounter issues such as jerky scrolling and unresponsive interfaces.

两者都阻止了浏览器; 在重绘或重排期间,用户或您的应用程序都无法执行其他任务。 在极端情况下,CSS效果可能会导致JavaScript执行速度变慢。 这是您遇到麻烦的滚动和无响应的界面等问题的原因之一。

It’s useful to understand when reflows are triggered:

了解何时触发重排很有用:

Adding, removing or changing visible DOM elements The first is obvious; using JavaScript to change the DOM will cause a reflow.

添加,删除或更改可见的DOM元素 使用JavaScript更改DOM将导致重排。

Adding, removing or changing CSS styles Similarly, directly applying CSS styles or changing the class may alter the layout. Changing the width of an element can affect all elements on the same DOM branch and those surrounding it.

添加,删除或更改CSS样式同样,直接应用CSS样式或更改类可能会更改布局。 更改元素的宽度会影响同一DOM分支上的所有元素及其周围的元素。

CSS3 animations and transitions Every frame of the animation will cause a reflow.

CSS3动画和过渡动画的每一帧都将导致重排。

Using offsetWidth and offsetHeight Bizarrely, reading an element’s offsetWidth and offsetHeight property can trigger an initial reflow so the figures can be calculated.

使用offsetWidth和offsetHeight奇怪的是,读取元素的offsetWidthoffsetHeight属性可以触发初始重排,因此可以计算出这些数字。

User actions Finally, the user can trigger reflows by activating a :hover effect, entering text in a field, resizing the window, changing the font dimensions, switching stylesheets or fonts.

用户操作最后,用户可以通过激活:hover效果,在字段中输入文本,调整窗口大小,更改字体尺寸,切换样式表或字体来触发重排。

The reflow processing flow hit will vary. Some browsers are better than others at certain operations. Some elements are more expensive to render than others. Fortunately, there are several general tips you can use to enhance performance.

回流处理流命中率将有所不同。 在某些操作上,某些浏览器比其他浏览器要好。 一些元素比其他元素更昂贵。 幸运的是,您可以使用一些通用技巧来提高性能。

1.使用最佳实践布局技术 (1. Use Best-Practice Layout Techniques)

I can’t believe I need to say this in 2015 but don’t use inline styles or tables for layout!

我不敢相信我要在2015年这么说,但不要使用内联样式或表格进行布局!

An inline style will affect layout as the HTML is downloaded and trigger an additional reflow. Tables are expensive because the parser requires more than one pass to calculate cell dimensions. Using table-layout: fixed can help when presenting tabular data since column widths are based on the header row content.

在下载HTML时,内联样式将影响布局并触发其他重排。 表格很昂贵,因为解析器需要多次通过才能计算单元格尺寸。 使用table-layout: fixed显示表格数据时会有所帮助,因为列宽基于标题行的内容。

Using flexbox for your main page layout can also have a performance hit because the position and dimensions of flex items can change as the HTML is downloaded.

由于在下载HTML时Flex项目的位置和尺寸可能会发生变化,因此将flexbox用于您的主页布局也可能会降低性能。

2.减少CSS规则的数量 (2. Minimize the Number of CSS Rules)

The fewer rules you use, the quicker the reflow. You should also avoid complex CSS selectors where possible.

您使用的规则越少,重排就越快。 您还应尽可能避免使用复杂CSS选择器。

This can be especially problematic if you’re using a framework such as Bootstrap — few sites use more than a fraction of the styles provided. Tools like Unused CSS, uCSS, grunt-uncss, and gulp-uncss can significantly reduce your style definitions and file sizes.

如果您使用的是诸如Bootstrap之类的框架,那么这可能会特别成问题-很少有网站使用所提供样式的一部分。 诸如未使用CSSuCSSgrunt-uncssgulp-uncss之类的工具可以显着减少样式定义和文件大小。

3.最小化DOM深度 (3. Minimize DOM depths)

Slightly trickier — reduce the size of your DOM tree and the number of elements in each branch. The smaller and shallower your document, the quicker it can be reflowed. It may be possible to remove unnecessary wrapper elements if you’re not supporting older browsers.

稍微棘手-减少DOM树的大小和每个分支中元素的数量。 您的文档越小越浅,则可以更快地重排它。 如果您不支持较旧的浏览器,则有可能删除不必要的包装器元素。

4.更新DOM树中的低类 (4. Update Classes Low in the DOM Tree)

Make class changes on elements as low in the DOM tree as possible (i.e. elements that don’t have multiple deeply nested children). This can limit the scope of the reflow to as few nodes as necessary. In essence, only apply class changes to parent nodes such as wrappers if the effect on nested children is minimal.

对DOM树中的元素进行尽可能小的类更改(即,没有多个深层嵌套子元素的元素)。 这样可以将重排的范围限制为必要的节点数。 本质上,如果对嵌套子级的影响很小,则仅将类更改应用于父级节点,例如包装器。

5.从流程中删除复杂的动画 (5. Remove Complex Animations From the Flow)

Ensure animations apply to a single element by removing them from the document flow with position: absolute; or position: fixed;. This permits the dimensions and position to be modified without affecting other elements in the document.

通过将动画从文档流中移到以下位置来确保将动画应用于单个元素position: absolute;position: fixed; 。 这允许在不影响文档中其他元素的情况下修改尺寸和位置。

6.修改隐藏元素 (6. Modify Hidden Elements)

Elements hidden with display: none; will not cause a repaint or reflow when they are changed. If practical, make changes to the element before making it visible.

display: none;隐藏的元素display: none; 更改它们时,不会导致重画或重排。 如果可行,请在对该元素进行显示之前对其进行更改。

7.批量更新元素 (7. Update Elements in Batch)

Performance can be improved by updating all DOM elements in a single operation. This simple example causes three reflows:

通过在单个操作中更新所有DOM元素,可以提高性能。 这个简单的示例导致三个重排:

var myelement = document.getElementById('myelement');
myelement.width = '100px';
myelement.height = '200px';
myelement.style.margin = '10px';

We can reduce this to a single reflow which is also easier to maintain, e.g.

我们可以将其减少到单个回流,这也易于维护,例如

var myelement = document.getElementById('myelement');
myelement.classList.add('newstyles');
.newstyles {
	width: 100px;
	height: 200px;
	margin: 10px;
}

You can also minimize the times you need to touch the DOM. Let’s assume you wanted to create this bullet list:

您还可以最小化触摸DOM所需的时间。 假设您要创建此项目符号列表:

  • item 1

    项目1
  • item 2

    项目2
  • item 3

    项目3

Adding each element one at a time causes up to seven reflows — one when the <ul> is appended, three for each <li> and three for the text. However, a single reflow can be implemented using a DOM fragment and building the nodes in memory first, e.g.

一次添加一个元素最多可导致七次重排-追加<ul>时一次,每个<li>三次,文本三则。 但是,可以使用DOM片段并首先在内存中构建节点来实现单个重排,例如

var
	i, li,
	frag = document.createDocumentFragment(),
	ul = frag.appendChild(document.createElement('ul'));

for (i = 1; i <= 3; i++) {
	li = ul.appendChild(document.createElement('li'));
	li.textContent = 'item ' + i;
}

document.body.appendChild(frag);

8.限制受影响的元素 (8. Limit the Affected Elements)

Avoid situations where a large number of elements could be affected. Consider a tabbed content control where clicking a tab activates a different content block. The surrounding elements would be affected if each content block had a different height. You may be able to improve performance by setting a fixed height for the container or removing the control from the document flow.

避免可能影响大量元素的情况。 考虑一个选项卡式内容控件,其中单击一个选项卡将激活另一个内容块。 如果每个内容块具有不同的高度,则会影响周围的元素。 您可以通过为容器设置固定高度或从文档流中删除控件来提高性能。

9.认识到平滑会损害性能 (9. Recognize that Smoothness Compromises Performance)

Moving an element one pixel at a time may look smooth but slower devices can struggle. Moving the element by four pixels per frame requires one quarter of the reflow processing and may only be slightly less smooth.

一次移动一个像素一个像素看起来很平滑,但较慢的设备可能会遇到困难。 每帧将元素移动四个像素需要回流处理的四分之一,并且平滑度可能会稍差一些。

10.使用浏览器工具分析重绘问题 (10. Analyze Repaint Issues with Browser Tools)

All mainstream browsers provide developer tools that highlight how reflows affect performance. In Blink/Webkit browsers such as Chrome, Safari, and Opera, open the Timeline panel and record an activity:

所有主流浏览器都提供了开发人员工具,这些工具可以重点介绍回流如何影响性能。 在Blink / Webkit浏览器(例如Chrome,Safari和Opera)中,打开“ 时间轴”面板并记录活动:

A similar Timeline panel is available in the Firefox Developer Tools:

Firefox开发人员工具中提供了类似的“ 时间轴”面板:

The panel is named UI Responsiveness in the Internet Explorer F12 Developer Tools:

该面板在Internet Explorer F12开发人员工具中名为UI响应

All browsers display reflow and repainting times in green. The tests above were simple examples not involving significant animation yet layout rendering requires more time than other factors such as scripting. Reduce your reflows and better performance will follow.

所有浏览器均以绿色显示重排和重涂时间。 上面的测试是简单的示例,不涉及大量动画,但是布局渲染比其他因素(例如脚本)需要更多的时间。 减少回流,将获得更好的性能。

If you’ve had success in improving performance in your animations and UIs using these or other suggestions, let us know in the comments.

如果您成功使用这些建议或其他建议提高了动画和UI的性能,请在评论中告知我们。

翻译自: https://www.sitepoint.com/10-ways-minimize-reflows-improve-performance/

减少重绘和回流的方法

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值