Browser process, performance indicators, performance optimization

Table of contents

Browser process: multi-process

Main process: display, interaction, adding and deleting processes

UI process: control address bar, bookmarks, forward and back

Stored processes: cookie, webstorage, indexDB

Rendering process: Each tab or window has an independent rendering process that parses HTML and executes js

Plug-in process

GPU process: image rendering

Network Process: Request

LightHouse v8/v9 performance indicators

FCP First Contentful Paint⭐

Optimization method: shorten font loading time

LCP Largest Contentful Paint⭐

reason

Slow server response speed

Render-blocking JavaScript and CSS

Slow resource loading speed

Client rendering

First pixel draw (FP) white screen ⭐

CLS (Cumulative Layout Shift): Cumulative layout offset, (measures the visual stability of web page elements)⭐

The most common reasons for poor CLS are: no dimensions, dynamic injection

Optimization means

1. Never insert content on top of existing content unless it is in response to user interaction

2. Tend to choose transform animation

TTI (Time to Interactive): time to become fully interactive

TBT (Total Blocking Time): blocking response time

Long Tasks: Long tasks are tasks that are executed on the browser's main thread and last longer than 50 milliseconds (usually)

Consequences: This may block the execution of other tasks, including responding to user input, execution of JavaScript scripts, DOM manipulation, CSS calculations, etc.

SI (Speed ​​Index): visual progression between frames

Optimization means: Reduce main thread work and JavaScript execution time

Time to first byte: the overall response time of the network backend

window.performance API

performance statistics

Level 1 specifications (window.performance.timing)

level2 specification (performance.getEntriesByType('navigation')[0])

Determine statistical starting point

fetchStart: Ready to fetch documents using HTTP requests

The time taken for browser redirection and page unloading does not play a big role in page loading analysis; fetchStart is usually used as the starting point for statistics.

Performance data calculation formula

Use performance.timing to simply calculate web page performance data

FCP首屏:domContentLoadedEventEnd/Start - fetchStart

FP white screen: domInteractive - fetchStart

Use performance.getEntries() to obtain time data for all resource requests

Use performance.getEntriesByName(name) to get time data for a specific name

FCP = performance.getEntriesByName("first-contentful-paint")[0].startTime - navigationStart

FP:item.startTime

LCP: Create a performance observerPerformanceObserver

Use performance.now() to accurately calculate program execution time

Manually measure performance using performance.mark and performance.measure

Google performance panel

SPA

Data reporting method

img tag using get request

performance optimization

Solve the problem of slow server response

Connect as early as possible: rel="preconnect"

DNS search as soon as possible: rel="dns-prefetc" (when preconnect is not supported)

cache

local

Static HTML cache to local disk

Service Worker 

acting

Configure reverse proxy (Varnish, nginx) to serve cached content

Route users to nearby CDN (Content Delivery Network)

Render-blocking JavaScript and CSS

Reduce CSS blocking time: reduce unnecessary characters css-minimizer-webpack-plugin

Lazy loading of non-critical CSS: rel="preload" before the main thread starts

Inline critical CSS:

Reduce JavaScript blocking time

Minify and compress JavaScript files:

Minification is the removal of spaces and unwanted code

Compression is the process of modifying data using compression algorithms

Static compression: WebpackPlugin

Lazy loading of unused JavaScript

code splitting

Slow resource loading speed

Optimize and compress images

Compress images (e.g. using Imagemin)

Convert images to newer formats (JPEG 2000, JPEG XR or WebP)

Use responsive images

Consider using an image CDN

Preload important resources: rel="preload"


Browser process: multi-process

Main process : display, interaction, adding and deleting processes

Browser Process

The main process is the core of the browser and is responsible for managing the user interface, display content, user interaction, etc.

It is also responsible for creating and destroying other processes, such as rendering processes, plug-in processes, etc.

UI process: control address bar, bookmarks, forward and back

Stored processes: cookie, webstorage, indexDB

Rendering process: Each tab or window has an independent rendering process that parses HTML and executes js

Renderer Process

Each tab or window has an independent rendering process.

The rendering process is responsible for parsing HTML, executing JavaScript, and rendering page content. It also has its own rendering engine and JavaScript engine.

This isolation prevents the crash of one page from affecting other pages.

Plug-in process

Plugin Process

If the page uses a plug-in (such as Flash, PDF reader, etc.), the browser will create an independent process for the plug-in to increase security and stability.

GPU process: image rendering

Some browsers use a separate GPU process to handle graphics rendering to improve performance and reduce the workload of the main rendering process.

Network Process: Request

Some browsers also place network requests and resource downloads in separate processes to better manage network connections.

LightHouse v8/v9 performance indicators

Lighthouse is an open source tool developed by Google for evaluating the quality of web applications in terms of performance, accessibility, best practices, and SEO (search engine optimization). Lighthouse can be used as a standalone CLI (command line interface) tool or can be run through the Chrome browser's developer tools.

FCPFirst content drawing ( First Contentful Paint)⭐

FCPIt measures the time it takes for the browser to render the first piece of DOM content after the user navigates to the page.

Images , non-white <canvas>elements , and content on the page svgare all considered DOMcontent;

iframeAnything within is not included

<iframe>(Inline frame) is a tag in HTML used to embed another web page or resource within the current web page. This can be used to display content from other websites in a page, or to integrate different web content into a single page

<!DOCTYPE html>
<html>
<head>
    <title>嵌入Google搜索</title>
</head>
<body>
    <h1>在页面中嵌入Google搜索</h1>
    
    <iframe src="https://www.google.com" width="800" height="600" frameborder="0"></iframe>
    
    <p>这是一个嵌入了Google搜索的示例。</p>
</body>
</html>

Optimization method : shorten font loading time

LCPMaximum content drawing ( Largest Contentful Paint)⭐

LCPMeasures when the largest content element in the viewport is rendered to the screen. This is as close as the user can see to the main content of the page

LCP data will be recorded through the PerformanceEntry object . Each time larger content is rendered, a new PerformanceEntry object will be generated.

reason

Slow server response speed

Render-blocking  JavaScript and CSS

Slow resource loading speed

Client rendering

First pixel draw (FP) white screen ⭐

Triggered from the start of the page load to when a render (any render) is detected in the browser (e.g. background changed, styles applied, etc.)

CLS( Cumulative Layout Shift): Cumulative layout offset, (measures the visual stability of web page components)⭐

Cumulative layout drift ( CLS) is an important user-centric metric for measuring visual stability

The most common reasons for poor CLS are: no dimensions, dynamic injection

1. Images without dimensions

2. Sizeless embedding andiframe

3. Dynamically injected content

Optimization means

1. Never insert content on top of existing content unless it is in response to user interaction

2. Tend to choose transformanimation

TTI( Time to Interactive): time to become fully interactive

TTIMeasure how long it takes for a page to become fully interactive

When the page displays

Useful content (measured by First Contentful Paint),

Event handlers are registered for most visible page elements

And when the page responds to user interaction within 50 milliseconds ,

Pages are considered fully interactive .

TBT( Total Blocking Time): Block response time

Long Tasks: Long tasks are tasks that are executed on the browser's main thread and last longer than 50 milliseconds (usually)

Consequences: This may block the execution of other tasks, including responding to user input, execution of JavaScript scripts, DOM manipulation, CSS calculations, etc.

It measures the delay in user interaction due to the presence of long tasks during page loading. The total TBT is the sum of the blocked portions of all long-running tasks during the loading of a web page .

For example, if a 70 millisecond long task is detected , the blocking portion will be 20 milliseconds .

It adds the duration of the blocking portion of these long tasks to get the total delay the user is likely to face . This includes all long-term tasks in the time period from FCP to TTI , because these tasks may affect the user's response speed to the page, thus affecting the user experience.

By monitoring and minimizing TBT sums, developers can work to improve the performance of web pages to ensure users can interact with the page faster and reduce potential interaction delays.

SI( Speed Index): visual progression between frames

SIThe index measures how quickly content is visually displayed during page load. LighthouseFirst capture the video of the page loading in the browser and calculate the visual progression between frames

Optimization meansJavaScript : Reduce the execution time of main thread work

Time to first byte: the overall response time of the network backend

The time it takes for the main document to return the first byte is an important indicator of page loading performance. It is generally imperceptible to users, but to developers, it represents the overall response time of accessing the network backend.

window.performance API

The performance API provides a lot of information related to web page performance and resource loading, which exists in the form of performance entries (Performance Entries). These performance items include navigation performance (such as page load time), resource loading performance (such as image, script and stylesheet load time)

// 获取所有资源加载性能条目
const resourceEntries = performance.getEntriesByType('resource');

// 遍历资源性能条目并打印
resourceEntries.forEach((entry) => {
    console.log('资源类型:', entry.initiatorType);
    console.log('资源 URL:', entry.name);
    console.log('加载时间:', entry.duration);
});

Get a performance entry of type "paint" from the performance API, then find and process the entry with the name 'first-contentful-paint', describe it as 'FCP' and add the start time to the transaction's page context after converting it to an integer middle.

// 获取性能信息并筛选出类型为 'paint' 的条目
window.performance
    .getEntries()
    .filter((entry: Record<string, any>) => {
        return entry.entryType === 'paint';
    })
    .forEach((item: Record<string, any>) => {
        // 如果条目的名称是 'first-contentful-paint',则执行以下操作
        if (item.name === 'first-contentful-paint') {
            // 将信息添加到事务的页面上下文中
            transaction.addPageContext({
                description: 'FCP', // 描述为 'FCP'
                time: floatToInt(item.startTime) // 将开始时间转换为整数并添加到 'time' 属性
            });
        }
    });

Performance It is a browser global object that provides a set of APIs for programmatically obtaining performance data of the program at certain nodes. It contains a set of high-precision time definitions and supporting related methods. We can print directly from the browser consolewindow.performance 

// 获取 performance 数据
var performance = {
    // memory 是非标准属性,只在 Chrome 有
    // 我有多少内存
    memory: {
        usedJSHeapSize:  16100000, // JS 对象(包括V8引擎内部对象)占用的内存,一定小于 totalJSHeapSize
        totalJSHeapSize: 35100000, // 可使用的内存
        jsHeapSizeLimit: 793000000 // 内存大小限制
    },

    // 我从哪里来?
    navigation: {
        redirectCount: 0, // 如果有重定向的话,页面通过几次重定向跳转而来
        type: 0           // 0   即 TYPE_NAVIGATENEXT 正常进入的页面(非刷新、非重定向等)
                          // 1   即 TYPE_RELOAD       通过 window.location.reload() 刷新的页面
                          // 2   即 TYPE_BACK_FORWARD 通过浏览器的前进后退按钮进入的页面(历史记录)
                          // 255 即 TYPE_UNDEFINED    非以上方式进入的页面
    },
//  核心时间相关
    timing: {
        // 在同一个浏览器上下文中,前一个网页(与当前页面不一定同域)unload 的时间戳,如果无前一个网页 unload ,则与 fetchStart 值相等
        navigationStart: 1441112691935,

        // 前一个网页(与当前页面同域)unload 的时间戳,如果无前一个网页 unload 或者前一个网页与当前页面不同域,则值为 0
        unloadEventStart: 0,

        // 和 unloadEventStart 相对应,返回前一个网页 unload 事件绑定的回调函数执行完毕的时间戳
        unloadEventEnd: 0,

        // 第一个 HTTP 重定向发生时的时间。有跳转且是同域名内的重定向才算,否则值为 0
        redirectStart: 0,

        // 最后一个 HTTP 重定向完成时的时间。有跳转且是同域名内部的重定向才算,否则值为 0
        redirectEnd: 0,

        // 浏览器准备好使用 HTTP 请求抓取文档的时间,这发生在检查本地缓存之前
        fetchStart: 1441112692155,

        // DNS 域名查询开始的时间,如果使用了本地缓存(即无 DNS 查询)或持久连接,则与 fetchStart 值相等
        domainLookupStart: 1441112692155,

        // DNS 域名查询完成的时间,如果使用了本地缓存(即无 DNS 查询)或持久连接,则与 fetchStart 值相等
        domainLookupEnd: 1441112692155,

        // HTTP(TCP) 开始建立连接的时间,如果是持久连接,则与 fetchStart 值相等
        // 注意如果在传输层发生了错误且重新建立连接,则这里显示的是新建立的连接开始的时间
        connectStart: 1441112692155,

        // HTTP(TCP) 完成建立连接的时间(完成握手),如果是持久连接,则与 fetchStart 值相等
        // 注意如果在传输层发生了错误且重新建立连接,则这里显示的是新建立的连接完成的时间
        // 注意这里握手结束,包括安全连接建立完成、SOCKS 授权通过
        connectEnd: 1441112692155,

        // HTTPS 连接开始的时间,如果不是安全连接,则值为 0
        secureConnectionStart: 0,

        // HTTP 请求读取真实文档开始的时间(完成建立连接),包括从本地读取缓存
        // 连接错误重连时,这里显示的也是新建立连接的时间
        requestStart: 1441112692158,

        // HTTP 开始接收响应的时间(获取到第一个字节),包括从本地读取缓存
        responseStart: 1441112692686,

        // HTTP 响应全部接收完成的时间(获取到最后一个字节),包括从本地读取缓存
        responseEnd: 1441112692687,

        // 开始解析渲染 DOM 树的时间,此时 Document.readyState 变为 loading,并将抛出 readystatechange 相关事件
        domLoading: 1441112692690,

        // 完成解析 DOM 树的时间,Document.readyState 变为 interactive,并将抛出 readystatechange 相关事件
        // 注意只是 DOM 树解析完成,这时候并没有开始加载网页内的资源
        domInteractive: 1441112693093,

        // DOM 解析完成后,网页内资源加载开始的时间
        // 在 DOMContentLoaded 事件抛出前发生
        domContentLoadedEventStart: 1441112693093,

        // DOM 解析完成后,网页内资源加载完成的时间(如 JS 脚本加载执行完毕)
        domContentLoadedEventEnd: 1441112693101,

        // DOM 树解析完成,且资源也准备就绪的时间,Document.readyState 变为 complete,并将抛出 readystatechange 相关事件
        domComplete: 1441112693214,

        // load 事件发送给文档,也即 load 回调函数开始执行的时间
        // 注意如果没有绑定 load 事件,值为 0
        loadEventStart: 1441112693214,

        // load 事件的回调函数执行完毕的时间
        loadEventEnd: 1441112693215

        // 按照字母排序
        // connectEnd: 1441112692155,
        // connectStart: 1441112692155,
        // domComplete: 1441112693214,
        // domContentLoadedEventEnd: 1441112693101,
        // domContentLoadedEventStart: 1441112693093,
        // domInteractive: 1441112693093,
        // domLoading: 1441112692690,
        // domainLookupEnd: 1441112692155,
        // domainLookupStart: 1441112692155,
        // fetchStart: 1441112692155,
        // loadEventEnd: 1441112693215,
        // loadEventStart: 1441112693214,
        // navigationStart: 1441112691935,
        // redirectEnd: 0,
        // redirectStart: 0,
        // requestStart: 1441112692158,
        // responseEnd: 1441112692687,
        // responseStart: 1441112692686,
        // secureConnectionStart: 0,
        // unloadEventEnd: 0,
        // unloadEventStart: 0
    }
}

performance statistics

Level 1 specifications (window.performance.timing)

  • performance.timing interface (defines 21 read-only properties from navigationStart to loadEventEnd)
  • performance.navigation (defines the navigation information of the current document, such as overloading or forward and backward, etc.)

v1.jpeg

Starting from the unloading of the old page in the current browser window to the completion of loading of the new page, the whole process is divided into 9 small blocks: prompt to unload old document, redirect/unload, application cache, DNS resolution, TCP handshake, HTTP request processing , HTTP response processing, DOM processing, document loading completed. Events are demarcated at the beginning, end and middle of each small block, Unix timestamps are taken, and the time difference is calculated between two events to obtain the time consuming of the intermediate process (accurate to the millisecond level).

v3.jpeg

level2 specification (performance.getEntriesByType('navigation')[0])

v2.jpeg

Determine statistical starting point

The starting point time for page performance statistics should be the time the user starts waiting after entering the URL and pressing Enter.

fetchStart: Ready to fetch documents using HTTP requests

The time taken for browser redirection and page unloading does not play a big role in page loading analysis; fetchStart is usually used as the starting point for statistics.

Performance data calculation formula

Easily performance.timing calculate web page performance data

FCP首屏:domContentLoadedEventEnd/Start - fetchStart

If you have indicators in a certain sense, you can use domContentLoadedEventEnd - fetchStart, or even loadEventStart - fetchStart. At this time, the page DOM tree has been parsed and the content is displayed.

The page is fully loaded (first rendering time + DOM parsing time + synchronous JS execution + resource loading time):

data['loadEventStart'] - data['fetchStart']

FP white screen: domInteractive - fetchStart

At this point, the page begins to parse the DOM tree , and the first element rendered by the page will appear soon.

  • Redirect time consumption: redirectEnd - redirectStart

  • DNS query time: domainLookupEnd - domainLookupStart

  • TCP connection time: connectEnd - connectStart

  • HTTP request time: responseEnd - responseStart

  • It takes time to parse the dom tree: domComplete - domInteractive

  • DOM ready time: domContentLoadedEventEnd - navigationStart

 HTML loading completion time, that is, DOM Ready time

The page is fully loaded: first rendering time + DOM parsing time + synchronous JS execution + resource loading time

//性能数据调用的api
data = window.performance.getEntriesByType('navigation')
//若上述api不支持则使用(将废弃)
data = window.performance.timing
  • onload:loadEventEnd - navigationStart

performance.getEntries()Get time data for all resource requests using

let times = {};
let t = window.performance.timing;

// 优先使用 navigation v2  https://www.w3.org/TR/navigation-timing-2/
if (typeof win.PerformanceNavigationTiming === 'function') {
  try {
    var nt2Timing = performance.getEntriesByType('navigation')[0]
    if (nt2Timing) {
      t = nt2Timing
    }
  } catch (err) {
  }
}

//重定向时间
times.redirectTime = t.redirectEnd - t.redirectStart;

//dns查询耗时
times.dnsTime = t.domainLookupEnd - t.domainLookupStart;

//TTFB 读取页面第一个字节的时间
times.ttfbTime = t.responseStart - t.navigationStart;

//DNS 缓存时间
times.appcacheTime = t.domainLookupStart - t.fetchStart;

//卸载页面的时间
times.unloadTime = t.unloadEventEnd - t.unloadEventStart;

//tcp连接耗时
times.tcpTime = t.connectEnd - t.connectStart;

//request请求耗时
times.reqTime = t.responseEnd - t.responseStart;

//解析dom树耗时
times.analysisTime = t.domComplete - t.domInteractive;

//白屏时间 
times.blankTime = (t.domInteractive || t.domLoading) - t.fetchStart;

//domReadyTime
times.domReadyTime = t.domContentLoadedEventEnd - t.fetchStart;

Get the time data of all resource requests. This function returns an array of objects sorted by startTime.

Let's output it directly to the panel.

11.png

performance.getEntriesByName(name)Get time data for a specific name using

FCP = performance.getEntriesByName("first-contentful-paint")[0].startTime - navigationStart

FP:item.startTime

window.performance
    .getEntries()
    .filter((entry: Record<string, any>) => {
      return entry.entryType === 'paint'
    }).forEach((item: Record<string, any>) => {
      if (item.name === 'first-paint') {
        transaction.addPageContext({
          description: 'FP',
          time: floatToInt(item.startTime)
        })
      } 
    })

LCP: Create a performance observerPerformanceObserver

// 创建性能观察器
const observer = new PerformanceObserver((entryList) => {
    // 从观察到的条目中提取性能条目
    const entries = list.getEntries();
    // 获取最后一个性能条目
    const lastEntry = perfEntries[perfEntries.length - 1];
    // 从最后一个性能条目中提取最大内容渲染时间 (LCP)
    const lcp = lastEntry.renderTime || lastEntry.loadTime;
    // 打印最大内容渲染时间 (LCP)
    console.log('LCP:', lcp);
});

// 开始观察指定类型的性能条目(最大内容渲染)
observer.observe({ entryTypes: ['largest-contentful-paint'] });

Use performance.now()precise calculation of program execution time

performance.nowThe method returns the number of microseconds (thousandths of a millisecond) between the current web page performance.timing.navigationStartand the current time . In other words, its accuracy can reach one millionth of a second.

Then we can finally calculate the precise time-consuming of a certain js operation through two calls.

const start = performance.now();
doTasks(); // 这里是耗时操作
const end = performance.now();
console.log("耗时:" + (end - start) + "微秒。");

Use performance.markand performance.measuremanually measure performance

It is recommended that you directly visit here to view this specific code example.

If we want to customize the collection of performance data indicators as a front-end performance monitoring system , then these two APIs are very powerful.

Google performance panel

let times = {};
let t = window.performance.timing;

// 优先使用 navigation v2  https://www.w3.org/TR/navigation-timing-2/
if (typeof win.PerformanceNavigationTiming === 'function') {
  try {
    var nt2Timing = performance.getEntriesByType('navigation')[0]
    if (nt2Timing) {
      t = nt2Timing
    }
  } catch (err) {
  }
}

//重定向时间
times.redirectTime = t.redirectEnd - t.redirectStart;

//dns查询耗时
times.dnsTime = t.domainLookupEnd - t.domainLookupStart;

//TTFB 读取页面第一个字节的时间(TTFB有多种计算方式,相减的参数可以是 requestStart 或者 startTime)
times.ttfbTime = t.responseStart - t.requestStart;

//DNS 缓存时间
times.appcacheTime = t.domainLookupStart - t.fetchStart;

//卸载页面的时间
times.unloadTime = t.unloadEventEnd - t.unloadEventStart;

//tcp连接耗时
times.tcpTime = t.connectEnd - t.connectStart;

//(Trans)内容传输耗时
times.transTime = t.responseEnd - t.responseStart;

//解析dom树耗时
times.analysisTime = t.domComplete - t.domInteractive;

//白屏时间 
times.blankTime = (t.domInteractive || t.domLoading) - t.fetchStart;

//domReadyTime
times.domReadyTime = t.domContentLoadedEventEnd - t.fetchStart;

SPA

The timing of page content rendering has been changed. If the URL is changed in the SPA application but the page is not refreshed, it will not be updated. Therefore, it is impossible to obtain the page rendering time corresponding to each sub-route only through this API. If you need to report the re-render time of each subpage when routing is switched, you need to customize the report.

Data reporting method

After measuring the time, you need to send the data to the server. Page performance statistics have relatively low requirements on the loss rate, and performance statistics should be carried out without affecting the logic of the main process and page performance as much as possible.

img tag using get request

  • There is no AJAX cross-domain problem and cross-origin requests can be made.
  • Very old tag, no browser compatibility issues
var i = new Image();
i.onload = i.onerror = i.onabort = function () {
  i = i.onload = i.onerror = i.onabort = null;
}
i.src = url;

Most modern browsers support the navigator.sendBeacon method. This method can be used to send small amounts of statistical and diagnostic data, and is particularly suitable for reporting statistics.

  • The data is reliable, and the request can still be sent even if the browser is closed.
  • Asynchronous execution , will not affect the loading of the next page
  • API is easy to use
window.addEventListener('unload', logData, false);

function logData() {
    navigator.sendBeacon("/log", analyticsData);
}

performance optimization

Solve the problem of slow server response

{Time to First Byte}( TTFB): Server response time

Connect early:rel="preconnect"

Use rel="preconnect"to tell the browser that your page intends to establish a connection as soon as possible.

<link rel="preconnect" href="https://example.com" />

ASAP DNS lookup:rel="dns-prefetc" (not supported preconnect时)

<link rel="dns-prefetch" href="https://example.com" />

cache

local

Static HTML cache to local disk

Service Worker 

It will run in the background of the browser and can intercept requests from the server. This level of programmatic cache control makes it possible to cache some or all of an HTML page's content and update the cache only when the content changes.

acting

Configure reverse proxy (Varnish, nginx) to serve cached content

Route users to nearby CDN (Content Delivery Network)

Routing users to nearby CDNs (Content Delivery Networks) is a strategy to optimize network performance and user experience. This process usually involves the following steps:

  1. CDN selection and configuration: First, website owners need to select one or more CDN providers, and then deploy the content of their website to these CDNs. This usually involves copying static resources (such as images, scripts, stylesheets) to a CDN server.

  2. Global CDN nodes: CDN providers typically have multiple nodes or server locations around the world. These nodes are distributed geographically, often in different cities and countries. The aim is to get closer to the end user, reduce data transfer delays and increase content loading speed.

  3. DNS resolution: When a user tries to access a website, their browser will issue a DNS (Domain Name System) request to resolve the domain name into an IP address. This step is called DNS resolution. If the website has CDN enabled, DNS resolution will usually return the IP address of the CDN node closest to the user's geographical location .

  4. Content caching and delivery: Once the user's request is routed to a nearby CDN node, the CDN server is responsible for responding to the request. If the requested content is already cached on the CDN, it will serve the content directly from the cache, thus reducing the response time of the request. If the content is not already cached, the CDN server will fetch the content from the origin server and cache it for future requests.

  5. Content delivery to the user: The CDN node will deliver the requested content to the user’s device, typically via the fastest network path. This helps reduce network latency and speed up content loading. CDNs can also further improve user experience by providing compression, load balancing , and other performance optimizations.

  6. Dynamic content and edge computing: In addition to static resources, some CDNs also provide edge computing services , allowing dynamic content and application logic to be run on CDN nodes to accelerate the delivery of dynamic content.

Overall, routing users to nearby CDN nodes helps improve website performance, reduce loading times, improve user experience, and reduce network traffic costs. This strategy is especially important for globally distributed websites and applications because it can reduce the negative impact of geographic distance on performance.

Render-blocking JavaScript and CSS

Reduce CSSblocking time: reduce unnecessary characterscss-minimizer-webpack-plugin

Cut CSS: CSSFiles can contain characters such as spaces , indents , or comments . None of these characters are necessary for the browser, and pruning the files ensures that they are removed. Using a module bundler or build tool, you can include a corresponding plugin in it to trim the CSS files on every build: For webpack5:css-minimizer-webpack-plugin i

Lazy loading non-critical CSS : before main thread startsrel="preload"

Use Code CoverageChrome in Developer Tools to find any unused code on the page .CSS


For any files that are not required for initial renderingCSS , use to load files asynchronously, using and . loadCSS rel="preload"onload
<link rel="preload" href="stylesheet.css" as="style" onload="this.rel='stylesheet'">

<link>The value of the element's relattribute allows you to declare a fetch request in preloadHTML , specifying resources that the page will need soon, and you want to start loading these resources early in the page life cycle, before the browser's main thread is started .<head>

Inline key CSS:<head>

Inline any critical path CSS used for above-the-fold content <head>by including it directly.CSS

Reduce JavaScriptblocking time

Minify and compress JavaScriptfiles:


Minification is the removal of spaces and unwanted code

The process of thereby creating a smaller but completely valid code file. Terseris a popular JavaScriptcompression tool;


Compression is the process of modifying data using compression algorithms

GzipIs the most widely used compression format for server and client interaction. Brotliis a newer compression algorithm that can provide Gzipbetter compression results than


Static compression:WebpackPlugin

Involves compressing and saving assets ahead of time. This makes the build process take longer, especially when using high compression levels , but ensures that the browser gets the compressed resources without lag. If your webserver supports it Brotli, then include it in the build step BrotliWebpackPluginby compressing the assets using a plugin such as . webpackOtherwise, use compress your assets CompressionPluginvia .gzip

Lazy loading of unusedJavaScript

code splitting


Reduce load through code splittingJavaScript ,-SplitChunksPlugin

Minimize unusedpolyfill

Slow resource loading speed

Optimize and compress images

For many websites, images are the largest elements in view after the page has finished loading . Common examples of this include splash images, large carousels, or banner images

Improving the time it takes for these types of images to load and render will directly increase the speed of LCP. Method to realize:

First consider not using images . If the image is irrelevant to the content, delete it.

Compress images (e.g. Imageminusing

Convert images to newer formats (JPEG 2000, JPEG XR or WebP)

Use responsive images

Consider using an image CDN

Preload important resources:rel="preload"

Sometimes, important resources declared or used in an CSSor file may be fetched later than expected, such as a font buried deep in one of the application's many CSS files .JavaScript

Know that a specific resource should be obtained first, please use <link rel="preload">to obtain the resource in a more timely manner

Many types of resources can be preloaded, but you should focus on preloading critical assets first , such as fonts , above-the-fold images or videos , and critical path CSS or JavaScript

<link rel="preload" as="script" href="script.js" />

<link rel="preload" as="style" href="style.css" />

<link rel="preload" as="image" href="img.png" />

Compressed text file

Compression algorithms such as Gzipand Brotlican significantly reduce the size of text files ( , , ) transferred between the server and the browser . Effectively supported by all browsers , it works in almost all newer browsers and provides better compression results.HTMLCSSJavaScriptGzipBrotli

First, check if your server has automatically compressed files . Most hosting platforms, CDNs, and reverse proxy servers compress-encode assets by default or enable you to easily configure them .

If you need to modify your server to allow it to compress files, consider using Brotliinstead gzip, as Brotliit can provide better compression ratios .

Once you've chosen the compression algorithm you want to use, compress your assets ahead of time during the build process , rather than in real time when the browser requests them. This minimizes server overhead and prevents delays in making requests, especially when using high compression ratios.

Use Service Workercached assets

Service WorkerCan be used to cache any static resource and serve it directly to the browser when repeated requests are received, without going through the network.

Using Service Workerprecached key resources can significantly reduce resource load times

Guess you like

Origin blog.csdn.net/qq_28838891/article/details/132612197