preface

Hello, I am Shark brother ~

This is the elder brother of the shark in 2022 the first article is what is going to write the first article positioning related front-end performance Old pink actually know performance optimization article I said as early as in June last year to do all sorts of things the delay After rectified Are across years before a fan of direct messages I asked what time out this performance optimization article to remind me Ha ha, feel still owe a lot of articles didn’t update) this article I will not introduce front-end performance optimization method of concrete Because I think writing specific how to optimize too much We mainly to focus on how to analyze their system front-end performance bottlenecks in where Look at your code performance to how many points is exciting But the article is a bit long The previous theory introduction will be a little bit too much, you can collect it for the convenience of checking and making up for the deficiency in the future. Finally, thank you very much for a classmate of Brother Shark’s former team (Kang Zhi) to help organize it. Welcome to click the link to join brother Shark’s front group to discuss technology

If you think this article is helpful, please remember to like three lian Oh, thank you very much!


Implications for performance optimization

1. Performance is an important part of user retention

  • Pinterest rebuilt their pages for performance, reducing perceived wait times by 40%, resulting in a 15% increase in search engine traffic and registrations.

  • By reducing the average page load time by 850 milliseconds, COOK found that they were able to increase conversion rates by 7%, reduce bounce rates by 7%, and increase the number of pages per page by 10%.

  • The BBC found that they lost 10% of their users every second their site loaded.

  • DoubleClick by Google found that 53% of users give up on a mobile site if a page takes longer than three seconds to load.

2. Performance is a critical part of improving conversion

  • For Mobify, every 100 ms reduction in homepage loading speed resulted in a 1.11% increase in saction-based conversions and an increase in average annual revenue of nearly $380,000. In addition, the checkout page load time was reduced by 100 ms and session-based conversions increased by 1.55%, resulting in an annual revenue increase of nearly $530,000
  • DoubleClick found that publishers that loaded their sites in five seconds earned twice as much AD revenue as those that loaded their sites in 19 seconds. When AutoAnything cut page load times in half, their sales increased by 12-13%.

What are the performance criteria from a user perspective

The famous 2-5-8 rule

  • When users can get a response within 2 seconds, they will feel that the response of the system is fast.

  • When the user gets the response between 2-5 seconds, the response speed of the system will feel ok;

  • When users get a response within 5-8 seconds, they will feel that the response speed of the system is slow but acceptable.

  • When the user still doesn’t get a response after more than eight seconds, he or she feels bad about the system, or thinks it’s unresponsive, and leaves the Web site or makes a second request.

To sum up: the performance of a website is the basis of retaining users and realizing cash

And our goal is to fight for 1s and save 2s

The 1s difference, it seems like a very small difference, but the 1s, the browser can actually do a lot of things so let’s look at how do we do performance analysis on a website

Common Website performance indicators

  1. FP First Paint Time: triggered when a render (any render) is detected from the start of the page load in the browser (e.g. background changes, style application, etc.)

If the screen is blank for too long, users will think that our page is unusable or unusable

  1. FCP (First Contentful Paint): The time from the time the page starts to load to the time any portion of the page content appears on the screen. (The focus is on content, a metric that tells when users receive useful information (text, images, etc.).)

  2. FMP First Meaningful Paint: The point at which the “main content” of a page begins to appear on the screen. This metric varies by page logic, so there is no specification. (This is just the beginning of the loading experience. If the page displays a boot image or loading animation, this moment is meaningless to the user.)

  3. Largest Contentful Paint (LCP) : The LCP indicator represents the rendering time of the Largest visible image or text block in a window. (It helps to capture more of the loading performance after the first render, but this metric is too complex, difficult to interpret, and error-prone to determine when the main content is finished loading.)

  4. Long Task: Tasks consumed when the execution time of a task exceeds 50ms (50ms threshold is a conclusion summarized from RAIL model, which is a conclusion obtained from Google’s research on user perception, which is similar to the threshold of user perception/patience. For tasks exceeding this threshold, users will perceive page lag)

  5. TTI (Time To Internative) : The Time from the start of a page until its main child resources are loaded To respond quickly To user input. (No time-consuming tasks)

  6. First Input Delay FID (First Input Delay): The time from the user’s first interaction with the page until the browser can actually start processing events. (Click, type, key)

  7. Total Blocking time (TBT) : Measures the total blocking time of the main thread from FCP to TTI.

  1. DCL (DOMContentLoaded) : The DOMContentLoaded event is fired after the HTML document has been fully loaded and parsed, without waiting for styles, images, and subframes to complete loading.

  2. L (onLoaded) : this function is triggered when all dependent resources are loaded

  3. CLS (Cumulative Layout Shift) : is a collection of all offset points Layout, complete all the page life cycle of unexpected Layout offset are included. Layout offset occurs at any time when a visible element changes its position from one render frame to the next

What’s the difference between thinking ==$. Ready and window.onload? = =

There are 11 performance metrics and you don’t have to understand the definition of every single one of them but let’s look at some of the core performance metrics that we need to focus on

Google Web Vitals – User experience quantification

Web-vitals: Google put forward a new way to quantify user experience on May 5, 2020. The launch of Web Vitals is to simplify the learning curve. Just pay attention to the performance of Web Vitals indicators.

Web-vitals integrates apis for 5 metrics, with 3 core metrics;

  • LCP time to display maximum content elements (a measure of site first load speed)
  • FID First input delay (to measure site interaction)
  • CLS Cumulative layout transfer (measure visual stability of web components)

<script type="module">
    import {getCLS, getFID,getFCP,getTTFB, getLCP} from 'https://unpkg.com/web-vitals?module';
    getCLS(console.log);
    getFID(console.log);
    getLCP(console.log);
    getFCP(console.log);
    getTTFB(console.log);
</script>
Copy the code

We can print these key indicators directly by reference to the measurement method

So far we know that the LCP, FID, CLS are the core but if we want to know more about the way performance is measured how do we do that let’s move on

Performance API

Performance is a browser global object that provides a set of apis for programmatically retrieving Performance data for a program at certain nodes. It contains a set of high-precision time definitions and associated methods. We can print window.performance directly on the browser console as follows

// Get performance data
var performance = {
    // Memory is a nonstandard property, available only in Chrome
    // How much memory do I have
    memory: {
        usedJSHeapSize:  16100000.// JS objects (including V8 internal objects) must take up less memory than totalJSHeapSize
        totalJSHeapSize: 35100000.// Available memory
        jsHeapSizeLimit: 793000000 // Memory size limit
    },

    Where do I come from?
    navigation: {
        redirectCount: 0.// The page is redirected several times, if any
        type: 0           // 0 is TYPE_NAVIGATENEXT's normal page (not refreshed, not redirected, etc.)
                          // 1 is the page that TYPE_RELOAD refreshes via window.location.reload()
                          // 2 i.e. TYPE_BACK_FORWARD page entered through the browser's forward and back buttons (history)
                          // 255: TYPE_UNDEFINED The page that is not entered in the above way
    },
// Core time is relevant
    timing: {
        // In the same browser context, the timestamp for the previous page (not necessarily the same domain as the current page) to unload, or equal to the fetchStart value if there was no previous page unload
        navigationStart: 1441112691935.// Time stamp of previous page unload (same domain as current page), 0 if there is no previous page unload or if previous page is in a different domain than current page
        unloadEventStart: 0.// Corresponding to unloadEventStart, returns the timestamp when the callback function bound with the Unload event on the previous page has finished executing
        unloadEventEnd: 0.// The time when the first HTTP redirect occurs. The value is 0 only when there is a redirect within the same domain name
        redirectStart: 0.// The time when the last HTTP redirect was completed. The value is 0 only when there is a redirect within the same domain name
        redirectEnd: 0.// The time when the browser is ready to grab the document using an HTTP request, before checking the local cache
        fetchStart: 1441112692155.// Start time of DNS domain name query. If local cache (no DNS query) or persistent connection is used, this value is the same as fetchStart value
        domainLookupStart: 1441112692155.// Time when DNS domain name query is completed. If local cache is used (that is, no DNS query is performed) or persistent connection is used, this value is the same as the fetchStart value
        domainLookupEnd: 1441112692155.// The time when the HTTP (TCP) connection is started, equal to the fetchStart value if the connection is persistent
        // Note that if an error occurs at the transport layer and the connection is re-established, this displays the time when the newly established connection started
        connectStart: 1441112692155.// The time HTTP (TCP) takes to complete the connection establishment (complete the handshake), equal to the fetchStart value if the connection is persistent
        // Note that if an error occurs at the transport layer and the connection is re-established, this displays the time when the newly established connection is completed
        // Note that the handshake is complete, including the establishment of the security connection and the SOCKS authorization
        connectEnd: 1441112692155.// The time when the HTTPS connection starts. If the connection is not secure, the value is 0
        secureConnectionStart: 0.// The time the HTTP request starts to read the real document (the connection is completed), including reading from the local cache
        // When a connection error reconnects, the time of the new connection is displayed here
        requestStart: 1441112692158.// The time when HTTP starts receiving the response (the first byte is retrieved), including reading from the local cache
        responseStart: 1441112692686.// The time when the HTTP response is fully received (fetched to the last byte), including reading from the local cache
        responseEnd: 1441112692687.// Start parsing the rendering time of the DOM tree, document. readyState becomes loading, and the readyStatechange event is thrown
        domLoading: 1441112692690.// When the DOM tree is parsed, document. readyState becomes interactive, and readyStatechange events are thrown
        // Note that only the DOM tree has been parsed, and no resources within the page have been loaded
        domInteractive: 1441112693093.// The time when resources in the web page start loading after DOM parsing is complete
        // occurs before the DOMContentLoaded event is thrown
        domContentLoadedEventStart: 1441112693093.// The time when the resources in the web page are loaded after the DOM parsing is completed (e.g. the JS script is loaded and executed)
        domContentLoadedEventEnd: 1441112693101.// When the DOM tree is parsed and the resource is ready, document. readyState becomes complete and the readyStatechange event is thrown
        domComplete: 1441112693214.// The load event is sent to the document, which is when the LOAD callback starts executing
        // Note that if no load event is bound, the value is 0
        loadEventStart: 1441112693214.// The time when the callback of the load event completes
        loadEventEnd: 1441112693215

        // Sort alphabetically
        // 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}}Copy the code

Seeing so many attributes for the first time, you must be as confused as this picture, what is this ghost?

Before we panic, let’s take a look at some of the key moments when the page loads

useperformance.timingThe information is simply computedWeb page Performance Data

  • FP: responseStart – navigationStart

  • Redirection time: redirectEnd – redirectStart

  • DNS query time: domainLookupEnd – domainLookupStart

  • TCP connection time: connectEnd – connectStart

  • HTTP request time: responseEnd -responsestart

  • Parsing dom tree takes time: domcomplete-dominteractive

  • DOM Ready time: domContentLoadedEventEnd – navigationStart

  • Onload: loadEventEnd – navigationStart

useperformance.getEntries()Gets time data for all resource requests

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

Let’s go straight to panel output.

useperformance.getEntriesByName(name)Gets time data for a specific name

For example, how to calculate the FCP first screen time

We can retrieve FCP data via the API provided by getEntriesByName(Name)

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

useperformance.now()Calculate program execution time accurately

Performance. A now method returns since the performance for the current page. Timing. NavigationStart between the current time on the number of milliseconds (ms) one over one thousand. That means it can be accurate to a millionth of a second.

Then we can calculate the exact time of a JS operation with two calls

const start = performance.now();
doTasks(); // This is a time consuming operation
const end = performance.now();
console.log("Time:" + (end - start) + "Microseconds.");
Copy the code

useperformance.markAs well asperformance.measureManual measurement of performance

This specific code example is recommended for viewing directly here

If we want to customize the collection of performance data metrics for front-end performance monitoring system, then these two apis are very powerful

“Ok” to introduce a series of code above level to collect and let’s front end performance index of measuring method There are some students may be asked if he might not see the calculation formula of so many head all big There were a look will understand more simple solution Then an introduction is to use the tools in the local how to analyze the performance of his website

Google performance panel

This is also called Performance, but it refers to our browser’s Performance panel tool

The overall structure

We may be surprised at first glance by these colorful patches of color and let’s not be afraid to take you through them

There are four regions from top to bottom

1: toolbar, including recording, refreshing page analysis, clearing results and a series of operations

2: Overview, high level of time line changes, including FPS, CPU, NET

3: flame diagram, analyze the selected area from different angles. For example: Network, Frames, Interactions, Main, etc

4: Overall reporting: analysis down to the millisecond level, and collation of events by call level

Toolbar area

Above the red box from left to right let’s put the mouse on you can see a few English words

  • Record Records the performance of a browser during a period of time
  • The Reload Page is used to record the performance of the web page from the initial loading to the completion of all resources. When clicked, the page automatically reloads
  • Screenshots displays dynamically loaded images of a page
  • Memory Views various memory usage changes

Now we can open up any site and click the second button to start the reload page analysis

The overview area

1. FPS: Frames Per Second, representing the number of Frames transmitted Per Second, is a unit of speed used to analyze a major performance indicator of animation. 1fps = 0.304 meter/ SEC (m /s). As shown in the figure above, the higher the green vertical line, the higher the FPS. Red indicates long frames, which may stall.

  • Experience of different frames:
  • Animations at 50-60 FPS will be smooth and comfortable;
  • Animation between 30 and 50 FPS, due to different sensitivity, comfort from person to person;
  • Animation at a frame rate of less than 30 FPS makes people feel sluggish and uncomfortable. Animation with large frame rate fluctuations can also make people feel stuck.

2. CPU: indicates the CPU resources. This area diagram indicates the type of event that consumes CPU resources. The colors in the figure are (consistent with the Summary color data representation in the overall report) :

  • Blue (Loading) : Indicates the time of network communication and HTML parsing.
  • Yellow (Scripting) : Indicates JavaScript execution time.
  • Purple Rendering: represents style calculation and layout time.
  • Green (Painting) : repainting time.
  • Gray (other) : Indicates the time taken by other events.
  • Idle white: indicates the Idle time.

3. NET: Each colored bar represents a resource. The longer the bar, the longer it takes to retrieve the resource. The light-colored part of each bar represents the wait time (from the time the resource is requested to the time the first byte is downloaded)

Flame figure

  1. Network: indicates the loading status of each server resource.

  2. Frames: Represents the performance of each frame, which can be combined with the FPS overview above

  3. Timings:

  • DCL (DOMContentLoaded) represents the HTML document loading completion event. Triggered when the initial HTML document is fully loaded and parsed, without waiting for styles, images, and subframes to finish. In obvious contrast, the load event is triggered when the page is fully loaded.
  • FP (First Paint) The time when the First screen is drawn.
  • FCP (First ContentfulPaint) First screen content draw, the First time to draw any text, image, non-blank canvas or SVG.
  • FMP (First MeaningfulPaint) Specifies meaningful content to be drawn on the First screen. This “MeaningfulPaint” has no authority and is essentially an algorithm that guesses at a point in time that it might be FMP. Largest ContentfulPaint (LCP) is used to draw the Largest element. FP, FCP and FMP are the same dashed line, and the time of the three is inconsistent. For example, after the first rendering, there may be JS blocking, in which case FCP will be greater than FP.
  • L (Onload) Event that all resources on the page are loaded.
  • Largest Contentful Paint LCP (Largest Contentful Paint) Specifies the time for drawing the Largest element on a page.

Careful students may have found that the indicators here are corresponding to the performance indicators mentioned earlier, so you can directly see the values of several core indicators on the page in the Performance panel

  1. Main: records the execution record of the Main thread in the rendering process. Click Main to see the specific situation of the execution of a taskAnalyzing specific functions takes timeThe most frequently viewed panel

    First of all, there are many tasks in the panel. If the Task takes a long time, it will be marked in red on the upper right corner. In this case, we can select the Task marked in red and zoom in to see its specific time.

    So if YOU zoom in, you can see what you’re doing, what functions are taking how much time, and you can see the compressed code, and you can see the compressed function name. Then we click on a function, and at the bottom of the panel, we get information about the code, which function it is, how long it takes, what line it is in which file, etc.

    This makes it easy to locate the time consuming function and optimize it accordingly

  2. Compositor Execution record of the Compositor thread, which records layer compositing operations after the HTML Paint phase

  3. Raster Raster thread pool, used to make gpus perform rasterized tasks

  4. GPU can intuitively see when GPU acceleration is enabled

  5. The Memory option, when checked, displays a line chartIn this graph, we can see the memory usage of the page, for example, JS Heap. If the curve keeps growing, it indicates that there is a memory leak. If the memory curve does not decrease for a long time, there is a possibility of a memory leak.

In fact, the fire map is enough for us to focus on the 1234 core of the appeal, and if we want to analyze memory leaks, we can check the memory option

Overall the report

Summary: indicates a statistical report on the time usage of indicators

The color here means the same thing as the CPU color in the overview area if you don’t know it, you can scroll up

In general, there are two areas to focus on: the yellow area, which represents script execution time, and the purple render time

1. Loading events

content instructions
Parse HTML Browser parsing HTML
Finish Loading Network Request completion
Receive Data The response data of the request arrives at the event, which may be triggered multiple times if the response data is large (unpacked)
Receive Response Triggered when the response header packet arrives
Send Request Triggered when a network request is sent
  1. Scripting event
content instructions
AnimationFrameFired Triggered when a defined animation frame occurs and the callback processing begins
Cancel Animation Frame Triggered when canceling an animation frame
GC Event Triggered when garbage is collected
DOMContentLoaded Triggered when the DOM content in the page has been loaded and parsed
Evaluate Script A script was evaluated.
Event JS event
Function Call Triggered when the browser enters the JS engine
Install Timer Triggered when a timer is created (calling setTimeout() and setInterval())
Request Animation Frame A requestAnimationFrame() call scheduled a new frame
Remove Timer Clear timer trigger
Time Triggered by a call to console.time()
Time End Triggered by a call to console.timeend ()
Timer Fired The timer is triggered after the callback is activated
XHR Ready State Change Triggered when an asynchronous request becomes ready
XHR Load Triggered when an asynchronous request has finished loading

3. The Rendering events

content instructions
Invalidate layout Triggered when a DOM change invalidates the page layout
Layout Triggered when page layout calculations are executed
Recalculate style Triggered when Chrome recalculates element styles
Scroll Triggered when the embedded window scrolls

4. The Painting

content instructions
Composite Layers Chrome’s rendering engine is triggered when the image layer is merged
Image Decode Trigger when an image resource completes decoding
Image Resize Trigger when an image is resized
Paint Triggered when the merged layer is drawn to the corresponding display area

5.Stystem: System use

E.g. There is no Idle time

Bottom-up: indicates the event time-sorted list (in reverse order).

There are two columns of Time data, one is “Self Time” represents the Time consumed by the task itself, and the other is “Total Time” represents the Total Time consumed by the task and its invoked subtasks. These two columns of data have different uses. You can decide which column of data to use as the sorting field according to your own requirements.

On the right side of the Activity, there is also a Source Map link, which can be clicked to locate the code corresponding to the corresponding operation. It makes it easier to locate specific code.

Call Tree: Represents a list of events called in sequence

The contents of the Call Tree can also be seen in the bottom-up without significant difference.

Event Log: indicates the sequence list of events

The Event Log contains a large amount of data and is recorded in sequence. It is not typically used in common optimization levels. If it’s a large application, opening it may cause Chrome to freeze.

Ok, by now, we have learned how to debug the Performance panel. You can open your website to see if there are some performance problems while reading the article. Of course, in addition to performance, we also have a more convenient tool, which automatically helps us analyze the performance and gives optimization suggestions

lighthouse

First of all, lighthouse provides the Google DevTools, The Google plug-in, and the NPM CLI application.

Let’s choose Generate Report to start our analysis! Take a look at the results first

We found Lighthouse and PerformanceThat’s a big differenceWhy is that?

Lighthouse works by defaultThe throttling process. We can not check throttling and also directly click View Trace to generate the corresponding performance panel data.

Lighthouse focuses on five main areas of analysis.

The Performance properties of

FCP, SP, LCP, TTI, TBI and CLS are listed.

Also availableTo optimize theplan

Accessibility

Accessibility: Refers to the design of accessibility, also known as site accessibility. The creation of a web site that is available/accessible to all users, regardless of their physical abilities and regardless of how they access the site.

Best Practice

In practical application, website security problem

SEO Search engine optimization

Search engine optimization (SEO) is the use of search engine rules to improve the natural ranking of web sites within relevant search engines

Progressive Web App Light Apps – Offline apps

PWA: Use modern Web apis and traditional incremental enhancement strategies to create cross-platform Web applications. These apps are ubiquitous and feature-rich, giving them the same user experience advantages as native apps;

How to build a simple PWA

So some of you might say can I use Lighthouse to test performance without a browser and the answer is absolutely yes

Let’s implement Lighthouse again using the NPM CLI

node cli lighthouse

Installation of Lighthouse

npm i -g lighthouse
lighthouse https://www.taobao.com
Copy the code

The results of

Some friends have the same problem

We can see the solution: you need to execute under powerShell commands

$env:CHROME_PATH = (Get-Process -Name chrome)[0].Path
Copy the code

What’s the difference between powerShell, CMD, and bash? Kind of stupid to tell the difference!

To sum up, powerShell combines the old CMD functionality with the built-in scripting/cmdlet instruction set, and it’s the strongest.

Finally, let’s take a look at the commands lighthouse supports on the CLI

lighthouse --help
// There are too many commands
--output             // Document report output support HTML, JSON, CSV, default HTML;
--view               // Data is displayed in HTML after analysis
--only-categories    // Analysis categories include "accessibility, best-practices, performance, PWA, SEO"
--throttling-method  // Traffic limiting methods: provide the current device environment, DevTools development mode, and Simulate mobile phones
--form-factor        // Support devices, mobile, desktop
Copy the code

summary

This article introduces in detail the technology related to front-end performance positioning, from meaning to performance API and finally to the use of performance tools. The overall difficulty is relatively high, so we need to cooperate with the actual operation practice. In fact, performance optimization is never an armchair battle Continuously summarize the performance problems and optimization suggestions of the web page to choose the most suitable optimization scheme and the topic of performance optimization is the core point whether in the interview or in the actual work. Only by mastering the method of performance bottleneck analysis can we help us to better treat the symptoms. Finally, I wish you all can harvest a satisfactory offer in 2022 Love and career double harvest!

Links to previous articles

  • The most complete Vue interview questions + detailed answers
  • From byte to foreign company, is this the way you ever wanted to go
  • The most complete handwritten JS programming problem
  • The latest front-end factory surface classics (detailed answer)
  • The most complete TypeScript learning guide ever

Shark’s front-end fishing skills

Welcome everyone technical exchange push touch fish help all can – link