Browser rendering optimization for front-end performance optimization

Article Directory

introduction

In today's era of rapid Internet development, users have higher and higher requirements for web page loading speed and performance. As front-end developers, we need to pay attention and work on improving the loading and rendering performance of web pages to provide a better user experience. Browser rendering optimization is the key to achieving this goal. In this article, we will discuss some tips and strategies on browser rendering optimization, aiming to help you optimize the rendering process of web pages and improve page loading speed and performance. Whether you are just getting started as a front-end developer or an experienced developer, this article will provide you with some valuable advice and practical tips to make your web pages render faster in the browser. Let's explore together how to improve web page performance through browser rendering optimization!

1. Browser rendering process

The browser rendering process refers to the process in which the browser parses, lays out, draws, and finally displays resources such as HTML, CSS, and JavaScript obtained from the server to the user . The following is a simple flowchart of browser rendering:

  1. Parsing HTML : The browser parses HTMLthe document from the top, building a DOM(Document Object Model) tree. DOMThe tree represents HTMLthe structure of the document, including tags, attributes, and text nodes.

  2. Parsing CSS : The browser parses the external CSSfile and applies the style rules to DOMthe corresponding elements in the tree. The parsing CSSprocess produces an CSSOM( CSSobject model) tree, which is DOMsimilar to a tree but represents CSSstyle information.

  3. Build a render tree (Render Tree) : The browser merges DOMthe tree and CSSOMthe tree to build a render tree. The render tree only contains visible elements that need to be displayed in the page, for example invisible elements (eg display:none) will not be included in the render tree.

  4. Layout : The browser calculates the size and position of each element in the rendering tree on the page, and determines their box model ( Box Model) information. This process is called layout or reflow( reflow), and it calculates the exact position of each element based on some CSSproperties (such as etc.).width、height、position

  5. Paint : The browser starts to draw each element to the screen based on the information about the render tree and the layout. The drawing process converts each element into one or more layers and uses GPUacceleration techniques to improve performance.

  6. Rasterization : After drawing is complete, the browser slices the layer into small tiles and converts them to bitmaps. This process is called rasterization, and it converts graphics into pixels that can be displayed on the screen.

  7. Composition : The browser composites all tiles in the correct order and outputs the final rendering result. This process is called compositing, and it draws the bitmap to the screen, constantly updating the rendering based on user interaction.

The whole process can be shown in the form of a flowchart as follows:

开始 -> 解析HTML -> 样式计算 -> 布局计算 -> 绘制 -> 合成 -> 结束

In summary, the browser rendering process includes steps such as parsing HTML, parsing CSS, building a rendering tree, layout, drawing, rasterization, and compositing. These steps convert HTML、CSSand JavaScriptconvert web pages into visible web content, allowing users to browse the web normally.

在这里补充一点
In the last step of the browser rendering process, Composition mainly does the following work :

  1. Synthesize the rendering tree : the composition engine will combine the page elements into one or more layers according to the structure and style attribute information of the rendering tree. These layers can be drawn and composited independently as desired.

  2. Layer drawing : In the compositing stage, the compositing engine will draw each layer into a bitmap separately. This process usually takes place in the GPU, taking advantage of hardware acceleration capabilities to speed up drawing.

  3. Composition of layers : The composition engine synthesizes the drawn layers in the correct order. The compositing process will perform operations such as transparency mixing and masking on bitmaps of different layers, and finally generate a global bitmap to be displayed.

  4. Display and display list update : Finally, the compositing engine sends the generated global bitmap to the display through the display pipeline for display. At the same time, the compositing engine updates the page's display list to reflect the latest rendering.

In short, composition ( Composition) is the last step of the browser rendering process, which includes steps such as synthesizing the rendering tree, drawing and compositing layers, generating the final bitmap, and updating the display list, and finally displays the rendering result on the user's on the screen. These efforts help improve rendering performance and user experience.

2. Backflow

1. What is reflow

Reflow refers to the browser re-rendering part or all of the page layout. When the structure, style or layout properties of the page change, the browser will trigger reflow.

Reflow occurs during the layout phase of browser rendering. There are two main steps in the rendering process: layout and painting.

The layout stage means that the browser calculates the position and size of each element on the page according to the box model of the element, establishes the relationship between elements, and generates a layout tree (render tree). When the browser finds that the page structure or style has changed during the layout phase, it will trigger a reflow.

During the reflow process, the browser traverses the layout tree, calculates the position and size of each element, and updates the corresponding rendering information, then regenerates the layout tree and drawing tree, and finally draws.

It should be noted that reflow is a relatively performance-intensive operation, because when reflow occurs, the browser needs to recalculate the page layout and update related rendering information. Frequent reflows will cause the performance of the page to degrade, so the occurrence of reflows should be minimized during development to improve the performance of the page.

2. What operations can cause backflow

Browser rendering reflow (reflow) means that when the page layout and geometric properties change, the browser will recalculate the layout of elements and redraw them, which consumes a lot of performance . Here are some common situations where browser rendering reflows:

  1. Changing the window size : When the window size changes, the page layout will change, and the layout of the elements needs to be recalculated and redrawn.
window.addEventListener('resize', function () {
    
    
  // 窗口大小改变的操作
});
  1. Changing element size : When changing the width, height, inner and outer margins and other attributes of an element, it will trigger the browser to recalculate the layout of the element.
element.style.width = "200px";
element.style.height = "100px";
  1. Changing element position : When changing an element's position attributes (top, left, right, bottom), it will cause the layout of its surrounding elements.
element.style.position = "absolute";
element.style.left = "100px";
element.style.top = "50px";
  1. Adding or removing elements : When adding or removing elements, the layout of the entire page will change, and all elements need to recalculate the layout.
document.body.appendChild(newElement);
document.body.removeChild(elementToRemove);
  1. Modifying the content of an element : When the text content or HTML structure of an element is modified, it causes a re-layout of the element and its surrounding elements.
element.textContent = "New Content";
element.innerHTML = "<p>New HTML</p>";
  1. Calculate some properties : When getting some calculated properties (such as offsetWidth, offsetHeight, clientWidth, clientHeight, etc.), the browser needs to recalculate the layout of the element.
var width = element.offsetWidth;
var height = element.offsetHeight;

3. How to optimize for backflow

Reflow is the process by which the browser recalculates and redraws the layout of the web page, which is a very performance-consuming operation. Optimizing reflow can improve the rendering performance of web pages. Here are some commonly used methods:

1. Use transform and opacity instead of properties such as top, left and width to realize animation effects. Because transform and opacity will not cause reflow.

Suppose there is a button, and you want to display an animation effect when you click it, you can use transformand opacityto achieve it instead of using top, leftand and widthother attributes. Here is an example of a real case:

HTML structure:

<button id="myButton">点击我</button>

CSS styles:

#myButton {
    
    
  position: relative;
  padding: 10px 20px;
  background-color: blue;
  color: white;
  transform: scale(1);
  opacity: 1;
  transition: transform 0.3s, opacity 0.3s;
}

#myButton.clicked {
    
    
  transform: scale(0.8);
  opacity: 0;
}

JavaScript code:

var button = document.getElementById("myButton");
button.addEventListener("click", function() {
    
    
  button.classList.add("clicked");
});

In the example above, the button element has the initial transformand opacityattributes by default. When the button is clicked, clickedan animation effect is triggered by adding a class. This class will change the button's transformand opacityproperties to achieve scaling and fading effects.

Since transformand opacityproperty changes do not cause reflow, this animation method can provide a smoother user experience, especially when dealing with complex animation effects.

2. Try to use absolute positioning (position: absolute) to move elements instead of modifying the layout properties of elements. Because absolute positioning breaks away from the document flow, it won't cause other elements to re-layout.

Use absolute positioning ( position: absolute) to move elements out of the normal document flow and position them precisely, avoiding reflow.

Here is an example of a real case:

The HTML code is as follows:

<div class="container">
  <div class="box"></div>
</div>

The CSS style is as follows:

.container {
    
    
  position: relative;
  width: 300px;
  height: 200px;
  border: 1px solid #000;
}

.box {
    
    
  position: absolute;
  top: 50px;
  left: 50px;
  width: 100px;
  height: 100px;
  background-color: red;
}

In this case, .containera relatively positioned parent container .boxand an absolutely positioned child element. By setting the value and value .boxof the , it can be precisely positioned at the specified position of the .topleft.container

In this way, when changing .boxthe position of the element, it will not cause .containerthe size of the parent container or the layout properties of other elements to change, thereby avoiding the occurrence of reflow.

Summarize:

  • Set the to of the parent container ( .container) to create a reference point for relative positioning.positionrelative
  • Set the of a child element ( .box) to take its position out of the normal document flow.positionabsolute
  • Use topthe and leftattributes to precisely position child elements.

This way, by using absolute positioning, elements can be moved without changing their layout properties, thus avoiding reflow.

3. Avoid using table layout, because the content change of each cell of the table will cause reflow. A similar effect can be achieved using CSS display: table and display: table-cell.

A common use tableof layouts is to create a horizontally centered navigation menu, where the width of each menu item is dynamically adjusted based on the content.

Code using tablea layout might look like this:

<table class="nav">
  <tr>
    <td>菜单项1</td>
    <td>菜单项2</td>
    <td>菜单项3</td>
    <td>菜单项4</td>
  </tr>
</table>

However, this layout method will cause reflow, because the width of each cell needs to be dynamically adjusted according to the content.

One tableway to avoid using layout is to use CSS's display: tableand display: table-cellproperties to achieve a similar effect while avoiding reflow. The code looks like this:

<div class="nav">
  <div class="nav-item">菜单项1</div>
  <div class="nav-item">菜单项2</div>
  <div class="nav-item">菜单项3</div>
  <div class="nav-item">菜单项4</div>
</div>
.nav {
    
    
  display: table;
  width: 100%;
}

.nav-item {
    
    
  display: table-cell;
  text-align: center;
}

.nav-item:hover {
    
    
  background-color: gray;
}

In this example, an <div>element is used as the container of the navigation menu, which is set display: tableto simulate the effect of the table layout, and each menu item is used display: table-cellto simulate the cells in the table.

The advantage of this is that the width of each menu item will adapt to the content without causing reflow. In addition, CSS can be used to add styles to menu items, such as changing the background color when the mouse is hovered over.

In conclusion, by simulating the table layout using display: tableand display: table-cellattributes, reflow can be avoided and the layout and style can be controlled more flexibly.

4. To avoid modifying the style of the DOM element multiple times in the loop, you can first save the style to be modified in a variable, and then update the style of the DOM element at one time.

Take modifying the style of all elements in a list as an example, suppose there is a <ul> element, and you want to set the background color of all <li> elements in it to red. If the style of the DOM element is modified multiple times in the loop, it will cause multiple reflows and affect performance.

The following is a way to avoid reflow, first save the style that needs to be modified in an object, and then update the style of the DOM element at once:

// 获取<ul>元素
const list = document.querySelector('ul');

// 创建一个对象,存储需要修改的样式
const styles = {
    
    
  backgroundColor: 'red'
};

// 循环遍历所有的<li>元素
const items = list.getElementsByTagName('li');
for(let i = 0; i < items.length; i++) {
    
    
  // 将需要修改的样式应用到每个<li>元素
  Object.assign(items[i].style, styles);
}

As you can see from the above code, first use querySelector to obtain the <ul> element to be operated, and then create a styles object, which stores the style that needs to be modified. Here, only the background color is set to red. Next, use getElementsByTagName to obtain all <li> elements, and apply the stored style to each <li> element through loop traversal, and assign the style attribute on the styles object to the li element at one time through the Object.assign method style attribute.

In this way, the effect of setting the background color of all <li> elements to red is achieved, which avoids modifying the style of DOM elements multiple times in the loop, reduces the number of reflows, and improves performance.

5. To avoid frequently reading layout properties (such as offsetWidth, offsetHeightetc.), you can cache the values ​​of these properties for use.

In actual development, frequently reading layout attributes (such as offsetWidth, offsetHeightetc.) will cause the browser to frequently reflow (reflow), affecting page performance. To avoid this situation, the values ​​of these properties can be cached for use.

A practical use case is to get the height of an element while scrolling. In some scenarios, we need to obtain the height of the element for processing, but if we directly call to obtain the height in each scroll event offsetHeight, it will cause frequent reflows.

In order to avoid this situation, we can cache the height of the element after the page is loaded or the element is rendered, instead of reading it every scroll event.

The sample code is as follows:

// 获取元素
const element = document.getElementById('scrollElement');

// 缓存元素的高度
let cachedHeight = element.offsetHeight;

// 监听滚动事件
window.addEventListener('scroll', () => {
    
    
  // 使用缓存的高度进行处理
  // ...
});

In the above code, we cache the height of the element in cachedHeighta variable after the page loads or the element is rendered. Then, when the scroll event fires, we directly use the cached height for processing instead of calling offsetHeightget height every time.

Doing so can avoid frequent reading of layout properties, reduce the number of reflows, and improve page performance. It should be noted that in some special cases, such as when the height of an element changes dynamically, the height of the cache needs to be updated in time.

6. Use virtual DOM technology, such as frameworks such as React and Vue.js, to update only the changed part when the component is updated, rather than the entire DOM tree.

Frameworks that use virtual DOM technology, such as React and Vue.js, can avoid reflows by updating parts of the actual DOM tree by comparing changes to the virtual DOM tree.

To give a practical case to illustrate, suppose we have a user list, which contains multiple user information components. We want to implement a simple user search function. After the user enters a keyword, the list should display the matching user information.

First, in React, we can define a UserList component to render a list of users:

class UserList extends React.Component {
    
    
  render() {
    
    
    return (
      <div>
        {
    
    this.props.users.map(user => (
          <UserItem key={
    
    user.id} user={
    
    user} />
        ))}
      </div>
    );
  }
}

Similarly in Vue.js:

Vue.component('user-list', {
    
    
  props: ['users'],
  template: `
    <div>
      <user-item v-for="user in users" :key="user.id" :user="user" />
    </div>
  `,
});

The UserItem component is a component used to display information about a single user. We can add an input box to this component to enter search keywords:

class UserItem extends React.Component {
    
    
  constructor(props) {
    
    
    super(props);
    this.state = {
    
    
      search: '',
    };
  }

  handleSearchChange = (event) => {
    
    
    this.setState({
    
     search: event.target.value });
  }

  render() {
    
    
    const {
    
     user } = this.props;
    const {
    
     search } = this.state;

    return (
      <div>
        <h3>{
    
    user.name}</h3>
        <p>{
    
    user.email}</p>
        <input type="text" value={
    
    search} onChange={
    
    this.handleSearchChange} />
      </div>
    );
  }
}

In Vue.js, we can also implement similar logic:

Vue.component('user-item', {
    
    
  props: ['user'],
  data() {
    
    
    return {
    
    
      search: '',
    };
  },
  methods: {
    
    
    handleSearchChange(event) {
    
    
      this.search = event.target.value;
    },
  },
  template: `
    <div>
      <h3>{
     
     { user.name }}</h3>
      <p>{
     
     { user.email }}</p>
      <input type="text" v-model="search" />
    </div>
  `,
});

Now, whenever the user enters a keyword in any input box, the search state of the corresponding component will be updated. Since React and Vue.js use virtual DOM technology, they will compare the difference between the two virtual DOM trees before and after, and only update the changed part to the actual DOM tree.

Here, we only need to dynamically display user information in the UserItem component according to the search keywords. For example, in React:

class UserItem extends React.Component {
    
    
  // ...

  render() {
    
    
    const {
    
     user } = this.props;
    const {
    
     search } = this.state;

    if (search && !user.name.toLowerCase().includes(search.toLowerCase())) {
    
    
      // 不匹配搜索关键字时,返回null,不渲染该用户信息
      return null;
    }

    return (
      <div>
        <h3>{
    
    user.name}</h3>
        <p>{
    
    user.email}</p>
        <input type="text" value={
    
    search} onChange={
    
    this.handleSearchChange} />
      </div>
    );
  }
}

In Vue.js, you can use the v-if directive to achieve similar logic:

Vue.component('user-item', {
    
    
  // ...

  template: `
    <div v-if="!search || user.name.toLowerCase().includes(search.toLowerCase())">
      <h3>{
     
     { user.name }}</h3>
      <p>{
     
     { user.email }}</p>
      <input type="text" v-model="search" />
    </div>
  `,
});

In this way, whenever a user enters a keyword search, only the part of the matched user information is updated instead of the entire DOM tree. This avoids unnecessary reflows and improves performance.

7. Use the will-change property of CSS to tell the browser in advance that an element is about to be modified, and the browser can perform some optimizations on the element.

Setting an attribute of an element will-changeto an attribute tells the browser that the element is about to be modified, and that the browser can perform some optimizations on the element to avoid reflows. This improves performance and avoids unnecessary layout calculations.

Here is a will-changepractical example of using attributes:

HTML:

<div class="box">这是一个 Box</div>

CSS:

.box {
    
    
  width: 100px;
  height: 100px;
  background-color: red;
  transition: transform 1s ease-in-out;
}

.box:hover {
    
    
  transform: scale(1.2);
  will-change: transform;
}

In this case, when the mouse hovers over the box element, the element will be scaled. We set the attribute .box:hoverin the selector to tell the browser that it is the attribute that the element is about to be modified.will-changetransformtransform

This way, the browser knows to do some optimizations before the box element is scaled to avoid unnecessary reflows. transformFor example, browsers can prepare render layers before modification to prevent layout recalculations.

Using will-changeproperties can improve performance, especially when dealing with large elements that need to change or complex animations. However, misuse of will-changeattributes can cause performance issues, so be sure to only apply to necessary elements and attributes.

8. To avoid frequently modifying the structure of the DOM tree, some optimization strategies can be adopted, such as using Document Fragment (DocumentFragment) for batch insertion and deletion operations, or using string splicing to generate HTML code.

documentFragment
In a practical case, suppose there is a to-do list where users can add, delete and complete tasks. Whenever the user performs these operations, the structure of the DOM tree will be modified, which may cause frequent reflows and redraws, reducing performance and user experience.

In order to avoid frequently modifying the structure of the DOM tree, we can use document fragments for batch insert and delete operations. A document fragment is a lightweight DOM node container that can contain a set of nodes, but does not create actual nodes in the document.

The following is an actual case of batch insert using document fragments:

// 创建一个文档片段
var fragment = document.createDocumentFragment();

// 获取待办事项列表的容器元素
var container = document.getElementById('todoList');

// 待添加的任务数据
var tasks = ['任务1', '任务2', '任务3'];

// 循环遍历任务列表
tasks.forEach(function(task) {
    
    
  // 创建新的任务元素
  var item = document.createElement('li');
  item.textContent = task;
  
  // 将任务元素添加到文档片段中
  fragment.appendChild(item);
});

// 将文档片段一次性插入到容器中
container.appendChild(fragment);

In this case, we first create a document fragment fragment, then loop through the task list, create new task elements and add them to the document fragment. Finally, by inserting document fragments into the container at one time, frequent modification of the DOM tree structure is avoided, and the number of reflows is reduced.

Similarly, we can use document fragments for bulk delete operations. The following is an actual case of bulk deletion using document fragments:

// 创建一个文档片段
var fragment = document.createDocumentFragment();

// 获取待删除的任务元素列表
var deleteList = document.querySelectorAll('.delete');

// 遍历待删除的任务元素列表
Array.prototype.forEach.call(deleteList, function(item) {
    
    
  // 将任务元素从文档中移除并添加到文档片段中
  fragment.appendChild(item);
});

// 从容器中一次性删除文档片段中的任务元素
container.removeChild(fragment);

In this case, we first create a document fragment fragment, and then get the list of task elements to be deleted through querySelectorAll. Next, we iterate through the list, removing each task element from the document and adding it to the document fragment. Finally, by deleting document fragments from the container at one time, frequent modification of the DOM tree structure is avoided and the number of reflows is reduced.

By using document fragments for batch insert and delete operations, we can optimize DOM operations, reduce the number of reflows, and improve performance and user experience.

String concatenation:
Suppose we have a list of tasks to be completed, users can add new tasks through the input box and click the button to save. Whenever a user adds a new task, we need to dynamically add the new task to the list of tasks in the DOM tree. In order to avoid performance problems caused by frequently modifying the DOM tree structure, we can use string concatenation to generate HTML code, and insert the generated HTML into the DOM tree at one time.

<!DOCTYPE html>
<html>
<head>
  <title>待完成任务列表</title>
</head>
<body>
  <div id="taskList"></div>
  <input type="text" id="taskInput">
  <button id="addButton">Add Task</button>

  <script>
    var taskList = document.getElementById('taskList');
    var taskInput = document.getElementById('taskInput');
    var addButton = document.getElementById('addButton');
    var tasks = [];

    // 监听按钮点击事件
    addButton.addEventListener('click', function() {
      
      
      var taskName = taskInput.value;
      if (taskName) {
      
      
        tasks.push(taskName);

        // 使用字符串拼接生成HTML代码
        var html = '';
        for (var i = 0; i < tasks.length; i++) {
      
      
          html += '<div>' + tasks[i] + '</div>';
        }

        // 批量插入任务列表
        var fragment = document.createElement('div');
        fragment.innerHTML = html;
        taskList.appendChild(fragment);

        // 清空输入框
        taskInput.value = '';
      }
    });
  </script>
</body>
</html>

In the above case, when the user clicks the Add button, we generate HTML code by using string concatenation, and insert the generated HTML code into the task list in the DOM tree at one time. Through one-time insertion, frequent modification of the DOM tree structure can be avoided, thereby reducing the number of reflows and improving page performance.

9. Use debounce or throttle to reduce the number of frequent reflow calls, for example, use the debounce and throttle methods in the lodash library.

Anti-shake ( debounce) and throttling ( throttle) are commonly used optimization methods in front-end development, which are used to limit the execution times of certain frequently triggered events and improve web page performance and user experience.

Anti-shake : After an event is triggered, within the specified time, if the event is triggered again, the timing will be restarted. Only when the event is not triggered again within the specified time, the event handler will be executed. It is usually used to optimize events frequently triggered by users, such as real-time search in the input box. Anti-shake can prevent frequent requests from being sent when the user is continuously typing, but wait for the user to stop typing before making the request, reducing the number of requests and server pressure.

Throttling : After an event is triggered, within the specified time, no matter how many times the event is triggered, the event processing function will only be executed once. Usually used to limit some high-frequency events, such as page scrolling events. Throttling can limit the execution frequency of event processing functions, avoid performance problems caused by frequent triggering, and ensure the smoothness of page response.

The difference between the two lies in the timing of execution . Anti-shake is to wait for a period of time after the event is triggered before executing the event processing function, while throttling is to execute the event processing function immediately after the event is triggered, and only execute it once within the specified time . Anti-shake is suitable for events triggered frequently by users, while throttling is suitable for events triggered by high frequency.

The following is the sample code to implement anti-shake function and throttling function in JavaScript:

Implementation of anti-shake function:

function debounce(func, delay) {
    
    
    let timerId;
  
    return function() {
    
    
        clearTimeout(timerId);
        timerId = setTimeout(func, delay);
    }
}

// 使用示例
function handleDebounce() {
    
    
    console.log('Debounced function is called');
}

const debouncedFunc = debounce(handleDebounce, 300);
debouncedFunc(); // 只有在 300ms 内没有再次调用时才会执行 handleDebounce 函数

Implementation of the throttling function:

function throttle(func, delay) {
    
    
    let timerId;
    let lastExecTime = 0;
  
    return function() {
    
    
        const currentTime = Date.now();
        const elapsed = currentTime - lastExecTime;
        const context = this;
        const args = arguments;
        
        if (elapsed < delay) {
    
    
            clearTimeout(timerId);
            timerId = setTimeout(function() {
    
    
                lastExecTime = currentTime;
                func.apply(context, args);
            }, delay - elapsed);
        } else {
    
    
            lastExecTime = currentTime;
            func.apply(context, args);
        }
    }
}

// 使用示例
function handleThrottle() {
    
    
    console.log('Throttled function is called');
}

const throttledFunc = throttle(handleThrottle, 300);
throttledFunc(); // 间隔小于 300ms 时不执行 handleThrottle 函数,超过 300ms 才执行

Debounce and throttle are two methods used to limit the frequency of function execution, which can help us avoid the reflow problem caused by frequent calls. The following is a practical case to illustrate how to use debounce and throttle to reduce the number of reflows.

Suppose we have a search box, when the user is typing in the search box, we want to perform the search operation within 500 milliseconds after the user stops typing to reduce unnecessary network requests.

First, we need to import the lodash library, which provides debounce and throttle methods.

import {
    
     debounce, throttle } from 'lodash';

Then, we need to create a search function.

function search(query) {
    
    
  // 发起搜索请求的逻辑
  console.log('搜索关键词:', query);
}

Next, we can use the debounce method to create a new function that executes the search function 500 milliseconds after the user stops typing.

const debouncedSearch = debounce(search, 500);

Finally, we need to listen for user input events and call the debouncedSearch function.

const inputElement = document.querySelector('input');

inputElement.addEventListener('input', (event) => {
    
    
  const query = event.target.value;
  debouncedSearch(query);
});

This way, when the user types, the debouncedSearch function will only be called once in 500 milliseconds. If the user keeps typing within 500 milliseconds, the debouncedSearch function will not be called, avoiding frequent network requests.

Similarly, we can also use the throttle method to limit the execution frequency of the function. The difference between the throttle method and the debounce method is that the throttle will execute the function multiple times within a certain time interval, while the debounce will only take effect within the last call within the specified time. Depending on the situation, choosing the right method can help us reduce the number of reflows.

10. Using requestAnimationFrame instead of setInterval can improve browser performance.

Use requestAnimationFrame instead of setInterval to make uniform animation.
The above article records a practical case of how to use requestAnimationFramethe replacement . If you are interested, you can take a look.setInterval

When used setIntervalto make animations, there will be a fixed time interval to execute the code, but this time interval is inaccurate, because it JavaScriptis single-threaded, and the execution of the code may be affected by other tasks and events. This will cause the frame rate of the animation to be unstable, or even stutter.

As for requestAnimationFramethe method of use, the browser will determine the execution timing of the callback function according to its own refresh rate, so as to ensure that the frame rate of the animation is stable and smooth. At the same time, requestAnimationFramethe method will be executed before the browser's redrawing, which can better synchronize the animation with the browser's drawing process and avoid unnecessary redrawing.

In addition, requestAnimationFramethe method can also automatically pause when the animation is invisible, saving unnecessary computing resources.

In summary, using requestAnimationFrameoverrides setIntervalcan improve browser performance and allow for smoother and more efficient animations.

11. Minimize the number and complexity of elements on the page, and hide or delay loading elements that do not need to be displayed to reduce the occurrence of reflow.

By following the optimization strategy above, the backflow phenomenon can be effectively reduced or optimized, and the performance of the front-end developed web application can be improved.

Summarize

In this blog post, we dig into browser rendering optimization in front-end performance optimization. We learned that optimizing the browser rendering process is critical when building high-performance front-end applications. By understanding the browser's rendering process and adopting some effective optimization strategies, we can significantly improve application performance and user experience.

We detailed how to minimize the rendering hierarchy and reduce reflow redraw operations. By using proper HTML and CSS structure, and avoiding frequent DOM operations, we can reduce the number of times the browser recalculates the layout and repaints, thereby improving rendering efficiency.

Overall, optimizing browser rendering performance is one of the keys to improving front-end application performance. By understanding the browser's rendering process and adopting some effective optimization strategies, we can make our applications more efficient and responsive, thereby improving user satisfaction and experience

Guess you like

Origin blog.csdn.net/jieyucx/article/details/132469062