Front end performance optimization: rearrangement and redrawing

Enjoy 2021-05-03 18:23:27
end performance optimization rearrangement redrawing

rearrangement ( backflow reflow) Redraw (repaint)

Reference blog

Page generation process

Graphic process
Text interpretation
  1. HTML The parser will HTML It can be interpreted as DOM Trees

  2. CSS The parser will CSS It can be interpreted as CSSOM Trees

  3. Combine two trees to create a rendering tree (Render Tree), The process is called Attachment

  4. According to the layout of the browser , On screen “ draw ” Show all the nodes of the rendering tree

  5. Then draw the layout on the screen , Show the whole page

  6. The fourth and fifth steps are the most time-consuming , Together, it's called rendering

rearrangement ( backflow reflow)


  • When DOM The changes in the geometry of the elements affect the geometric information of the elements ( The position and size of the elements ), The browser needs to recalculate the geometric properties of the elements , Put it in the right place in the interface , This process is called rearrangement .
  • Simply put, it's about regenerating the layout , Rearrange elements .

What's going to happen ?

  • Initial rendering of the page , This is the most expensive rearrangement

  • Add and delete visible DOM Elements

  • Changing the position of elements

  • Change the size of the element : The total size of the elements = Wide and high ( Content filling )+ padding + Frame + Margin

  • Change element content : The number of words , Picture size, etc

  • Change the element font size

  • Change the browser window size :resize Event time

  • Activate CSS pseudo-classes

  • increase CSS Pseudo elements

  • Set up style The value of the property , Every setting will trigger a reflow

  • Query some properties or call some calculation methods :offsetWidth、offsetHeight etc. , besides , When we call getComputedStyle Method , perhaps IE Inside currentStyle when , It also triggers a rearrangement , The principle is the same , All for one “ Immediacy ” and “ accuracy ”.

  • Common causes rearrangement properties and methods -- -- --
    width height margin padding
    display border-width border position
    overflow font-size vertical-align min-height
    clientWidth clientHeight clientTop clientLeft
    offsetWudth offsetHeight offsetTop offsetLeft
    scrollWidth scrollHeight scrollTop scrollLeft
    scrollIntoView() scrollTo() getComputedStyle()
    getBoundingClientRect() scrollIntoViewIfNeeded()

Reordering the sphere of influence

Global scope ( avoid )
  • From the root node html Start to rearrange the entire rendering tree .
Local scope
  • Rearrange a part of the rendering tree or a rendering object
  • Will a DOM The wide and high geometric information of elements is dead , Trigger a rearrangement inside this element , Only elements inside that element are re rendered , It will not affect the outside world

Repaint (repaint)


  • When the appearance of an element changes , But it didn't change the layout , The process of redrawing the appearance of an element .

When will redrawing happen ?

  • attribute : -- -- --
    color border-style visibility background
    text-decoration background-image background-position background-repeat
    outline-color outline outline-style border-radius
    outline-width box-shadow background-size

Rearrangement versus redrawing

  • Both affect performance , But rearranging is more than redrawing , It's going to cost us a lot of performance

  • Redrawing does not necessarily lead to rearrangement , Rearrangement must lead to redrawing

    • Redrawing simply changes the appearance of the elements , Does not cause the page to regenerate the layout

    • When the browser has finished rearranging , Parts affected by this rearrangement will be redrawn .

Optimization plan

Reduce the scope of rearrangement

  • Try to organize in the form of local layout html structure , As little impact as possible on the scope of rearrangement (BFC)
  • Do not use table Layout , Maybe a small change will make the whole thing table relayout . Then I have to use table The occasion of , You can set table-layout:auto; Or is it table-layout:fixed This will allow table Line by line rendering , This is also to limit reflow Range of influence .

Reduce the number of rearrangements

1. Change the pattern set
  • For a page , It's wise and maintainable to change the class name rather than the style .

  • utilize style.cssText perhaps classname Batch modification

    • document.getElementById("d1").style.cssText = "color:red; font-size:13px;";
       Copy code 
2. Separate read and write operations ( Avoid forced refresh )
  • DOM Multiple read operations of ( Or multiple write operations ), It should be put together separately . Don't read between two operations , Add a write operation .

    • // bad Forced to refresh Trigger four rearrangements + Repaint = div.offsetLeft + 1 + 'px'; = div.offsetTop + 1 + 'px'; = div.offsetRight + 1 + 'px'; = div.offsetBottom + 1 + 'px';
      // good Cache layout information It's like separation of reading and writing Trigger a rearrangement + Repaint
      var curLeft = div.offsetLeft;
      var curTop = div.offsetTop;
      var curRight = div.offsetRight;
      var curBottom = div.offsetBottom; = curLeft + 1 + 'px'; = curTop + 1 + 'px'; = curRight + 1 + 'px'; = curBottom + 1 + 'px';
       Copy code 
Why only one rearrangement is triggered after read-write separation
  • It's all thanks to the browser's rendering queue mechanism

  • When we modify the geometric properties of an element , Causes the browser to trigger a rearrangement or redraw . It puts the operation in the render queue , Wait until the operation in the queue reaches a certain number or a certain time interval , The browser will perform these operations in batches .

    • = '10px'; = '10px'; = '20px'; = '20px';
      // There are four write operations in the rendering queue
      // At the first console When , involve div.offsetLeft Key styles , The browser immediately performs the task of rendering the queue , Clear the rendering queue of the above four write operations .
      // Because in the queue , There may be operations that affect these values ( namely console.log Operation to print the latest div.offsetLeft Value ), To give us the most accurate value , The browser will immediately rearrange + Repaint , So the queue is empty .
      // Be careful : Operations involving key attributes , At any time, the browser immediately performs the task of rendering the queue , Even if the value is not associated with the value modified in your operation .
      // The rest console, Because the rendering queue is empty , So there's no trigger for rearrangement , It's just worth it .
       Copy code 
    • Force the operation request to refresh the queue

      • offsetTop, offsetLeft, offsetWidth, offsetHeight scrollTop, scrollLeft, scrollWidth, scrollHeight clientTop, clientLeft, clientWidth, clientHeight getComputedStyle(), perhaps IE Of currentStyle
3. What will be revised DOM Element offline operation
1. Use display:none
  • Once we set the element display:none when ( There's only one rearrangement and redrawing ), Elements no longer exist in the rendering tree , It's like taking it off the page “ Remove ”, Our subsequent operations will not trigger rearrangement and redraw , After adding enough changes , adopt display Property display ( Another rearrangement and redrawing ), In this way, even a large number of changes trigger only two rearrangements .
2. Create fragment
  • adopt documentFragment Create a dom debris , Batch operation on it dom, After the operation , Add it to the document , This will only trigger a rearrangement .
3. Replication node
  • Replication node 【cloneNode(deep)】, Working on copies , Then replace 【replaceChild(newNode,oldNode)】 it !
4. Off stream
  • Using absolute positioning makes that element a separate element in the rendering tree body A child element of , Rearrangement costs less , It won't affect other nodes too much . When you place this element on these nodes , Some other nodes in this area may need to be redrawn , But there's no need to rearrange .
5. Optimize animation
  • You can apply complex animation effects to position The attribute is absolute or fixed Elements on , This has little effect on other elements .
  • Animation should also sacrifice some smoothness , In exchange for rendering speed : For example, to achieve an animation , With 1 It's smoothest to move in pixels , however Layout Too often , A lot of consumption CPU resources , If the 3 Moving in pixels is much better

  1. css单位
  2. CSS unit
  3. 前端验证集合
  4. Front end validation collection
  5. Front end learning (4) -- response line, response head, response body
  6. Lesson 27: using time measuring tools to explore available spare time
  7. CSS 单位
  8. CSS unit
  9. 前端工具集合
  10. Front end Tools Collection
  11. Introduction to HTTP message format
  12. Introduction to new features of HTML5
  13. Common instructions for Vue
  14. Introduction of bootstrap Blazer component library
  15. HTML5 速览
  16. HTML5 quick view
  17. HTML表格自动排序
  18. For less than $1700, create a private cloud with openstack
  19. Basic learning of JavaScript (1)
  20. 前端编程之路一一HTML标签分类
  21. Front end Programming: HTML tag classification
  22. ColSpan and rowspan merging cells of HTML form elements
  23. JavaScript 日期时间格式化
  24. JavaScript date time formatting
  25. Classification of front end interview questions - html2
  26. CSS block elements
  27. HTML5 form detailed tutorial
  28. HTML5 form detailed tutorial
  29. HTML5新增的元素表
  30. New element table in HTML5
  31. 3D轮播插件vue-carousel-3d非官方最全文档
  32. 3D carousel plug-in vue-carousel-3d
  33. Uniapp (Vue general) integrates Tencent location service SDK -- multi platform small program general
  34. Slowhttptest slow attack tool use details
  35. HTML summary (2)
  36. Overview of CSS3
  37. Front end abnormal monitoring system
  38. 免费网站部署和免费数据库Serverless云存储资源汇总整理
  39. Free website deployment and collection of free database serverless cloud storage resources
  40. Vux form -- a form solution of base vux
  41. 可以直接用于HTML中的特殊字符表 unicode字符集
  42. Can be directly used in HTML special character table Unicode character set
  43. Detailed explanation of HTTP protocol
  44. HTTP request header and request response header
  45. CSS background深度解析
  46. Python web/HTML GUI
  47. Front end standard 2: HTML you know and don't know
  48. Some HTML tags
  49. HTML标签之table
  50. Table of HTML tag
  51. DataTables of jQuery plug-in
  52. Unity calls Google's free translation API (HTTPS interface). Young people don't speak martial arts. How can they speak in multiple languages
  53. Linux entry most commonly used commands, do not learn a bunch of useless commands
  54. Piziheng embedded: a list of common short-range wireless communication protocols (Wi Fi / Bluetooth / ZigBee / thread...)
  55. Naming rules for the front end team of ladder
  56. HTML logo related symbols
  57. Node . JS: development resources and technology stack arrangement
  58. Unity calls Google's free translation API (HTTPS interface). Young people don't speak martial arts. How can they speak in multiple languages
  59. Straighten out JavaScript (18) - statements and operators
  60. Employment information statistics network (interface document)