preface

Page performance optimization is an important part of front-end development, and there are two commonly heard indicators to evaluate front-end performance: white screen time and first screen time.

Let’s take a look at what is the white screen time and the first screen time, how to calculate.

What is white screen and first screen time

White screen time (FP)

First Paint: The time between the time the browser responds to the user’s web address and the time the browser starts displaying content.

  • White screen time = the time when the page starts to display – the time when the request starts

First Screen Time (FCP)

First Contentful Paint: The time from the time the browser responds to the user’s web address to the time the First content is rendered.

  • First screen time = End time of first screen content rendering – start time of request

Conventional method of calculation

Bad time

The blank screen duration is calculated from the time when the user requests the page to the time when the content is displayed. The intermediate process includes DNS query, TCP connection establishment, sending of the first HTTP request, return of the HTML document, and the HEAD of the HTML document is parsed.

Therefore, the factors that affect the blank screen time are network, server performance, and front-end page structure design.

It is generally considered that the time when the browser starts rendering or parses is the point at which the white screen ends. So we can record one point in time before all static resources and embedded scripts/styles in the HEAD of an HTML document, and another point in time at the bottom of the head, and the difference between the two as the white screen time

Code implementation:

<! DOCTYPEhtml>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <title>White screen time calculation - general method</title>
  <script>
    window.pageStartTime = Date.now()
  </script>
  <link rel="stylesheet" href="Https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-assets/ionicons/2.0.1/css/ionicons.min.css~tplv-t2oaga2asx-image.ima ge">
  <link rel="stylesheet" href="https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-assets/asset/fw-icon/1.0.9/iconfont.css~tplv-t2oaga2asx-image.image">
  <script>
    window.firstPaint = Date.now()
    console.log('White screen time:The ${window.firstPaint - window.pageStartTime}`)
  </script>
</head>
<body>
  <div>This is an example page for calculating the white screen time in general</div>
</body>
</html>
Copy the code

White screen time = window.firstpaint-window.pagestartTime

One disadvantage of this approach is that you can’t get information about the time before the HTML document was parsed.

The first screen time

The first screen time should be known at two points: the start of the request time and the end of the first screen content rendering time. The start request time is the same as the white screen time. Here is how to get the end render time of the first screen content.

The end time of the first screen should be when the first screen of the page is drawn, but there is no specific API to get this point directly, so we have to use a trick. For example, if we want to know where the bottom of the first screen of content is in the HTML document, then the bottom of the first screen of content is also called the first screen line.

Now the question is: Where is the first screen line?

There are many different scenarios, and different scenarios have different calculation methods.

Marks the first screen label module

This is easier by adding a script to the HTML document at the location of the first screen line to get the time at that location.

However, we can only approximate a position where to add. Take the screen of a mobile phone for example, the screen size of different types of mobile phone is different. The position we take may be above or below the front screen line, and only an approximate value can be obtained.

Code implementation

<! DOCTYPEhtml>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <title>First screen Time calculation - Marks the first screen label module</title>
  <script>
    window.pageStartTime = Date.now()
  </script>
  <link rel="stylesheet" href="Https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-assets/ionicons/2.0.1/css/ionicons.min.css~tplv-t2oaga2asx-image.ima ge">
  <link rel="stylesheet" href="https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-assets/asset/fw-icon/1.0.9/iconfont.css~tplv-t2oaga2asx-image.image">
</head>

<body>
  <div>First screen Time calculation - Marks the first screen label module</div>
  <div class="module-1"></div>

  <div class="module-2"></div>

  <script type="text/javascript">
    window.firstScreen = Date.now();
    console.log('First screen time:The ${window.firstScreen - window.pageStartTime}`)
  </script>
  <div class="module-3"></div>

  <div class="module-4"></div>
</body>

</html>
Copy the code

FirstScreen time = window.firstscreen – window.pagestarttime

This method is applicable to the following scenarios:

  • There is no need to pull data in the first screen, otherwise the first screen may still be blank when the first screen line is obtained
  • Don’t worry about image loading, just the main module on the first screen

In business, where this algorithm is rarely used, most pages need to use interfaces, so this approach is rarely used

But if your page is static, or if asynchronous data doesn’t affect the overall first-screen experience, you can use this method

Statistics the slowest picture loading time on the first screen

We know that in a page, image resources are usually loaded later, so we can count whether the image with the slowest loading on the first screen is loaded, and record the end time.

How do I know which image loads slowest in the first screen?

We can take all the images in the first screen, walk through them, listen to the onload event of the image tag one by one, collect their load time, and finally compare to get the maximum load time.

Code implementation:

<! DOCTYPEhtml>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <title>First screen Time calculation - Collects the slowest picture loading time on the first screen</title>
  <script>
    window.pageStartTime = Date.now()
  </script>
</head>

<body>
  <img src="https://gitee.com/HanpengChen/blog-images/raw/master/blogImages/2021/spring/20210107155629.png" alt="img" onload="load()">
  <img src="https://gitee.com/HanpengChen/blog-images/raw/master/blogImages/2020/autumn/article-gzh-qrcode.png" alt="img" onload="load()">
  <script>
    function load() {
      window.firstScreen = Date.now()
    }
    window.onload = function () {
      // First screen time
      console.log(window.firstScreen - window.pageStartTime)
    }
  </script>
</body>
</html>
Copy the code

FirstScreen time = window.firstscreen – window.pagestarttime

Applicable scenarios:

  • A page with a fixed number of first screen elements, such as a mobile screen that displays the same amount of content regardless of screen size.

However, this scheme is not applicable to pages with unfixed elements on the first screen. The most typical one is PC pages, which display different contents on the first screen under different screen sizes. The above scheme does not apply to this scenario.

Custom module calculation method

This algorithm is similar to the method of marking the first screen, but also ignores the loading of images in the first screen. This method mainly considers asynchronous data.

In the first-screen label method, the first-screen blank caused by asynchronous data cannot be calculated, so its adaptation scenarios are very limited

Custom modules are calculated according to the latest time of the interface on the first screen

Code implementation:

<! DOCTYPEhtml>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <title>First screen time calculation - custom module calculation method</title>
  <script>
    window.pageStartTime = Date.now()
  </script>
</head>

<body>
  <div class="module-1"></div>

  <div class="module-2"></div>
  <script type="text/javascript">
    setTimeout(() = > {
      // Assume that the first screen loads the article list data asynchronously
      window.firstScreen = Date.now();
      console.log(window.firstScreen - window.pageStartTime)
    }, 500)
  </script>
  <div class="module-3"></div>
</body>

</html>
Copy the code

window.performance

The w3c now provides an API for measuring web pages and web applications: window.Performance, which makes it easier to get the corresponding time points.

This API is supported in Internet Explorer 9 and up.

Window.performance is an object in the browser that records key points during page loading and parsing. Placed in the Global environment, it is accessible through JavaScript.

Performance can be detected and compatible with:

var performance = window.performance || 
    window.msPerformance || 
    window.webkitPerformance;
if (performance) {
    // Your code
}
Copy the code

The performance properties

Let’s take a look at the properties of performance:

  • Memory: Displays the current memory usage, which is a dynamic value
    • UsedJSHeapSize: the memory occupied by the JS object
    • JsHeapSizeLimit: available memory
    • TotalJSHeapSize: Memory size limit

UsedJSHeapSize is not greater than totalJSHeapSize. If it is greater than totalJSHeapSize, a memory leak may occur.

  • Navigation: Displays information about the source of the page

    • RedirectCount: indicates how many redirects the page should take, if any. Default is 0
    • Type: indicates the page opening mode. 0- Normal entry; 1- the page refreshed via window.reload(); 2- Pages accessed through the browser’s forward and back buttons; 255- Pages not entered in the above manner.
  • Onresourcetimingbufferfull: in resourcetimingbufferfull event triggered when the called an event handler. Its value is a manually set callback that is executed when the browser’s resource time performance buffer is full.

  • TimeOrigin: A reference point in a series of time points, accurate to one thousandth of a millisecond.

  • Timing: a series of critical points in time, including network and parsing data.

Timing Point in time

Timing timing timing timing timing timing timing timing

  • NavigationStart: Timestamp at the end of an unload for a page on the same browser. If there is no previous page, this value is the same as fetchStart

  • UnloadEventStart: Timestamp when the previous page unload event was thrown. If there is no previous page, this value returns 0.

  • UnloadEventEnd: Corresponding to unloadEventStart, unload the timestamp when event processing is complete. If there is no previous page, this value returns 0.

  • RedirectStart: Timestamp when the first HTTP redirect starts. If there is no redirect, or a different source in the redirect, this value returns 0

  • RedirectEnd: Timestamp when the last HTTP redirect is completed (that is, when the last bit of the HTTP response was received directly). If there is no redirect, or a different source in the redirect, this value returns 0

  • FetchStart: The browser is ready to fetch the time stamp of the document using an HTTP request. This point in time is before any application caches are checked.

  • DomainLookupStart: UNIX timestamp from which DNS domain name queries start. If persistent Connection is used, or the information is stored in a cache or local resource, this value will be consistent with fetchStart.

  • DomainLookupEnd: indicates the time when the DNS domain name query is complete. Is equal to the fetchStart value if local caching (that is, no DNS query) or persistent connections are used

  • ConnectStart: indicates the timestamp when the HTTP (TCP) domain name query ends. If persistent Connection is used, or the information is stored in a cache or local resource, this value will be consistent with fetchStart.

  • ConnectEnd: HTTP (TCP) Returns the timestamp when the connection is established between the browser and the server. If a persistent connection is established, the return value is the same as the value of the fetchStart attribute. Connection establishment refers to the completion of all handshake and authentication processes.

  • SecureConnectionStart: HTTPS returns the timestamp when the handshake between the browser and the server began the secure connection. If the current page does not require a secure connection, 0 is returned.

  • RequestStart: Returns the timestamp when the browser made an HTTP request to the server (or started reading the local cache).

  • ResponseStart: Returns the timestamp when the browser received the first byte from the server (or read it from the local cache). If the transport layer fails after initiating the request and the connection is reopened, this property will be counted as the corresponding initiation time of the new request.

  • ResponseEnd: Returns when the browser received (or read from the local cache, or read from a local resource) the last byte from the server. (closes if the HTTP connection has been closed before).

  • DomLoading: Timestamp when the DOM structure of the current web page begins to parse (i.e., when the document. readyState property becomes “loading” and the corresponding readyStatechange event is triggered).

  • DomInteractive: Timestamp when the DOM structure of the current web page finishes parsing and starts loading the embedded resources (i.e., when the document. readyState property changes to “interactive” and the corresponding readyStatechange event is triggered).

  • DomContentLoadedEventStart: when the parser sends DOMContentLoaded event, i.e., all need to be performed the timestamp of when the script has been parsed.

  • DomContentLoadedEventEnd: when all need the immediate execution of a script has executed, no matter the execution order of timestamp.

  • DomComplete: Timestamp when the current Document is parsed, i.e. Document.readyState becomes ‘complete’ and the corresponding readyStatechange is triggered

  • LoadEventStart: Timestamp when the load event is sent. If the event has not already been sent, its value will be 0.

  • LoadEventEnd: The timestamp when the load event ends, i.e. the load event is complete. If the event has not yet been sent or completed, its value will be 0

Calculation of correlation time

From the above points, let’s see what time we can calculate:

  • 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
  • ResponseStart – navigationStart
  • DOM Ready time: domContentLoadedEventEnd – navigationStart
  • Onload time: loadEventEnd – navigationStart

Resource Performance API

Performance. Timing Records the overall performance indicators of the page. If you want to get performance metrics for individual resources (such as JS and images), you need to use the Resource Timing API.

Method performance.getentries (), which contains an array list of all static resources; Each item is a request associated with parameters such as name, type, time, and so on.

In addition to performance. GetEntries, Performance also contains a series of useful methods, such as:

  • performance.now()
  • Performance.getEntriesByName()
  • .

We can use getEntriesByName() to calculate the first screen time:

The first screen time: performance. GetEntriesByName (” first – contentful – paint “) [0]. StartTime – navigationStart

Should I calculate the first screen time or the white screen time?

The first screen time is more accurate than the white screen time in evaluating whether the page has started rendering, but the end times are often very close. So it’s up to you to decide which computing method to use depending on your business scenario.

For simple web pages with less interactivity, because the load is relatively fast, so the difference between the two is not big, so you can choose a calculation method according to your preference.

For large, complex pages, you may find that the white screen time and the first screen time are far apart due to the need to process more complex elements, so it is more useful to calculate the first screen time.

White screen and first screen optimization

At present, the common optimization schemes of white screen are:

  • SSR
  • pre-rendered
  • Skeleton screen

Methods to optimize the loading time of the first screen:

  • CDN Distribution (reduced transmission distance)
  • Back-end caching at the business layer
  • Static file caching scheme
  • Front-end dynamic loading of resources
  • Reduce the number of requests
  • Take advantage of HTTP compression

White screen time and first screen time optimization methods more than the above, interested partners can find relevant content.

If you find this helpful:

1. Click “like” to support it, so that more people can see this article

2, pay attention to the public account: FrontGeek technology (FrontGeek), we learn and progress together.