This is the sixth installment in the series, and the next installment covers Web page performance metrics as follows:

Many of the articles that people are looking at, including some published online, are about performance optimization techniques, but also about performance metrics and how to do performance monitoring, many of which are based on Web performance standards and browser implementations of Web performance standards. If we have a thorough understanding of Web performance standards, we know how performance metrics are defined, how they are calculated, and what optimization strategies are supported by browsers. Based on this understanding, we can talk about how to troubleshoot performance problems, how to optimize performance, and how to collect performance data for performance monitoring. The full list of performance STANDARDS is available from the Web Performance Working Group home page, AND can be searched on ALL STANDARDS AND DRAFTS. This article will take you through these Web performance standards in a systematic way. I’ve divided Web performance standards into two broad categories: performance measurement-related and optimization strategy-related. As I introduce each standard, I will introduce it in this order:

  • Usefulness of standards
  • Standard version
  • What the standard contains
  • Relationship to other standards

Performance measurement

Page performance concerns include page rendering time and smooth interaction. The shorter the page rendering time and the smoother the interaction, the better we think the page will perform. Users can make sensory judgments about performance, but as developers, we need to quantify performance and use performance metrics to measure performance. Major browsers now support specific apis for capturing page performance data. In the HTML specification, the Window object is defined. We can get a Window object from the Window. Many familiar apis are mounted on the Window, such as:

  • window.document
  • window.history
  • window.localStorage
  • window.location
  • window.navigator
  • window.postMessage
  • .

Each of these apis is defined by a different W3C standard, and the Web performance standard adds the Performance property to the window, which returns a performance object through window.performance.

Object contains a number of properties and methods used to measure performance, defined by various Web performance standards. Here are some of the specifications related to performance measurement.

High Resolution Time

The specification defines a JavaScript interface that provides the current time at millisecond resolution and is not affected by system clock skew or adjustment. There are two versions of this standard, Level 1 and Level 2. Level 2 is an official published standard, so Level 1 is outdated and is not recommended to be used anymore. We just need to know what specifications Level 2 defines.

Level 2 contains these:

  • 1. Define the Time Origin of measurement performance data

The performance data we obtain are time stamps, and an initial time is needed to calculate the time difference, that is, the time spent in a certain phase.

  • 2. High-precision timestamp DOMHighResTimeStamp is defined

Used to store time values in milliseconds. The apis defined by the Web performance specification fetch times with high-precision timestamps.

  • 3. Defines the Performance object and several properties and methods of the Performance object.

    • now()
    • timeOrigin
    • toJSON()

All performance data is obtained from the performance object returned by window.performance. The properties and methods defined by the following time-related performance criteria are in window.performance and performance objects.

The Performance object is originally defined in Navigation Timing Level 1

Now that you know what the specification defines, why is it called High Resolution Time? Because the main content of this specification is related to high precision time.

Performance Timeline

This standard extends the Performance objects defined in the HR-time 2 specification above by providing an interface to retrieve Performance measures based on specific filters (Name, EntryType), through which we can obtain timelines of Performance measures for multiple dimensions (pages, resources, and so on). There are currently two versions of this standard, Level 1 and Level 2. Level 1 is currently in the REC state, and the Level 2 specification is still in the draft stage. When the Level 2 specification is officially released, Level 1 will also be deprecated.

  • Performance Timeline (REC)
  • Performance Timeline Level 2  (WD) ✔︎

The Level 2 specification contains these:

  • 1,PerformanceObject adds three methods:

    • getEntries()
    • getEntriesByType()
    • getEntriesByName()

We can type this code in the browser console to see what Entry is.

window.performance.getEntries();
Copy the code

The result is:





  • PerformanceResourceTiming
  • PerformanceNavigationTiming
  • PerformancePaintTiming
  • PerformanceMark
  • PerformanceMeasure
  • PerformanceEventTiming
  • PerformanceServerTiming
  • .

These objects contain various performance data metrics for the entire life cycle of the Web application.

These objects are defined in other time-related specifications, so these time-related specifications all use PerformanceEntry as defined by the Performance Timeline specification.

So, we can get performance data for a specific name and entryType based on getEntriesByType() and getEntriesByName(). Such as:

performance.getEntriesByType('paint');
performance.getEntriesByName('https://www.google.com/images/nav_logo299.webp');
Copy the code

Their details are as follows:

Interface EntryType Name InitiatorType (type of request initiated)
PerformanceResourceTiming resource Resource URL Link, IMG, Script, CSS, FETCH, Beacon, iframe, other
PerformanceNavigationTiming navigation The page URL navigation
PerformancePaintTiming paint First – paint, first – contentful – paint /
PerformanceEventTiming first-input keydown /
PerformanceMark mark The name given when mark is created /
PerformanceMeasure measure The name given when measure is created /
PerformanceLongTaskTiming longtask Look here /

Entry Type represents the Type of PerformanceEntry object, and the W3C Performance Working Group has developed a specification for the registration of Entry Type names: Timing Entry Names Registry, this specification is currently in the Working Draft stage. Currently registered types include:

  • 2. DefinedPerformanceEntryobject

PerformanceEntry has properties such as Name, entryType, startTime, Duration, toJSON(), Is the public properties PerformanceResourceTiming, PerformanceNavigationTiming object, So that will be introduced later other specifications define objects (such as PerformanceResourceTiming, PerformanceNavigationTiming) inheritance.

  • 3. DefinedPerformanceObserverobject

Used to observe the performance timeline for notification when a new performance metric is recorded, which is often used when collecting performance data. For example, look at the performance data of type Resource and print it.

<! doctype html> <html> <head></head> <body> <img id="image0" src="https://www.w3.org/Icons/w3c_main.png" /> <script> const  resourceObserver = new PerformanceObserver(list => { list .getEntries() // Get the values we are interested in .map(({ name, entryType, startTime, fetchStart, responseStart, responseEnd }) => { const obj = { "Name": name, "Entry Type": entryType, "Start Time": startTime, "Fetch Start": fetchStart, "Response Start": responseStart, "Response End": responseEnd, }; return JSON.stringify(obj, null, 2); }) // Display them to the console. .forEach(console.log); // Disconnect after processing the events. resourceObserver.disconnect(); }); // Subscribe to new events for Resource Timing. resourceObserver.observe({type: "resource"}); / / multiple Entry Type / / userTimingObserver. Observe ({entryTypes: (" mark ", "measure")}); </script> </body> </html>Copy the code

Ok, now that you know what this specification defines, you can see why it’s called Performance Timeline. This specification provides an API for obtaining performance timelines for various types (Navigation, Resource, paint, etc.).

Resource Timing

This specification defines an API for accessing complete timing information about resources in a document, such as the start and end times of DNS, TCP, Request, etc., to help us gather loading timelines, resource sizes, and resource types for static resources in a document. There are two versions of the specification, Level 1 and Level 2. Level 1 was a candidate for recommendation in 2017 and has not been officially released to this day. Level 2 is currently in the working draft and will be updated as of 2020.02.18, but its relationship with Level 1 is not documented.

  • Resource Timing Level 1 (CR)
  • Resource Timing Level 2 (WD) ✔︎

There are few differences between the two versions, but Level 2 adds IANA Considerations for setting Timing- allow-Origin to temporary headers and updates the resource Timing model.

https://w3c.github.io/resource-timing/timestamp-diagram.svg


Resource timing processing model

The Level 2 specification contains these:

  • 1. DefinedPerformanceResourceTimingobject

This object describes the performance timeline of resource requests.


  • 2. Add the following methods to the Performance object

    • clearResourceTimings()
    • setResourceTimingBufferSize()


  • 3. DefinedTiming-Allow-OriginResponse headers

Request for cross-domain resources, access to the object of PerformanceResourceTiming (time) of the attribute value, because the cross-domain restrictions, the browser will not provide the resources performance data to the user, the time value will be set to 0. If a server adds timing-allow-Origin to the response header of a request resource, the browser will expose the performance time value of the resource to the user. We can obtain performance data for all resources in the document by:

performance.getEntriesByType('resource');
Copy the code

Or obtain performance data for a specific resource by:

performance.getEntriesByName('https://www.google.com/images/nav_logo299.webp');
Copy the code

The result is:

Ok, now that you know what this specification defines, you can see why this specification is called Resource Timing. This specification describes performance measures for resource request timing.

Navigation Timing

This standard defines a complete performance metric for document navigation, that is, the performance time of a document from the time it is requested to the time it is loaded. There are currently two versions of this standard. Level 1 was released in 2012 and Level 2 will be updated in January 2020. In the future, Level 2 will replace Level 1.

  • Navigation Timing Level 1 (REC)
  • Navigation Timing Level 2 (WD) ✔︎

Currently, many browsers have implemented Level 2. It is recommended to use the API defined by the Level 2 specification. The API defined by Level 1 is still in use by many people, so it will be described in detail below.


Navigation Timing Level 1

As mentioned earlier, the High Resolution Time API defines Performance objects, which are available through window.performance. For Navigation Timing Level 1, there are two additional attributes: Timing and Navigation. The specification contains the following:

  • PerformanceTiming

Used to measure the page performance, we can pass through the window. The performance. The timing for the performance data of the page, the meaning of each field in the object returned can PerformanceTiming | MDN look up.








https://www.w3.org/TR/navigation-timing/timing-overview.png


  • PerformanceNavigation object was defined

Used to describe the load related operations, through the window. The performance. The navigation, the returned PerformanceNavigation object storage the two properties, they are said to trigger the cause of the page is loaded. These can be page redirection, forward and back buttons, or plain OLD URL loading



PerformanceNavigation | MDN

  • 3. The window.performance property is defined

Added performance attribute to Window object: timing and navigation Navigation Timing Level 2

In 2019, the Web Performance Working Group introduced Navigation Timing Level 2, which will replace Navigation Timing Level 1. The two properties performance. Timing and performance. Navigation defined in Navigation Timing Level 1 are deprecated. Level 2 has the following new content. We can understand the changes in Level 2 after reading this section.

  • the definition of Performance interface was moved to [PERFORMANCE-TIMELINE-2];
  • builds on top of [RESOURCE-TIMING-2];
  • support for [PERFORMANCE-TIMELINE-2];
  • support for [HR-TIME-2];
  • support for prerender navigations [RESOURCE-HINTS];
  • exposes number of redirects since the last non-redirect navigation;
  • exposes next hop network protocol;
  • exposes transfer, encoded body and decoded body size information;
  • secureConnectionStart attribute is now mandatory.

The Level 2 specification contains the following:

  • 1. DefinedPerformanceNavigationTimingobject

This object is used to measure the performance of the document. We can obtain the performance data of the document in the following way. All Time values are measured from Origin Time.

window.performance.getEntriesByType("navigation");
Copy the code

This returns the following data:



PerformanceNavigationTiming | MDN

const [entry] = performance.getEntriesByType("navigation");
let proto = Object.getPrototypeOf(entry);

const protos = {};

while(proto.toString() ! ='[object Object]') {
	protos[proto.toString()] = Object.keys(proto);
	proto = Object.getPrototypeOf(proto);
}

console.log(protos);
Copy the code

The result is:

{
    "[object PerformanceNavigationTiming]":[
        "unloadEventStart",
        "unloadEventEnd",
        "domInteractive",
        "domContentLoadedEventStart",
        "domContentLoadedEventEnd",
        "domComplete",
        "loadEventStart",
        "loadEventEnd",
        "type",
        "redirectCount",
        "toJSON"
    ],
    "[object PerformanceResourceTiming]":
        "initiatorType",
        "nextHopProtocol",
        "workerStart",
        "redirectStart",
        "redirectEnd",
        "fetchStart",
        "domainLookupStart",
        "domainLookupEnd",
        "connectStart",
        "connectEnd",
        "secureConnectionStart",
        "requestStart",
        "responseStart",
        "responseEnd",
        "transferSize", 
        "encodedBodySize",
        "decodedBodySize",
        "serverTiming",
        "toJSON"
    ],
    "[object PerformanceEntry]":[
        "name",
        "entryType",
        "startTime",
        "duration",
        "toJSON"
    ]
}
Copy the code

You can see that the Navigation Timing Level 2 specification only defines these fields:

"unloadEventStart",
"unloadEventEnd",
"domInteractive",
"domContentLoadedEventStart",
"domContentLoadedEventEnd",
"domComplete",
"loadEventStart",
"loadEventEnd",
"type",
"redirectCount",
"toJSON"
Copy the code

The type and redirectCount is abandoned Navigation Timing Level 1 standard Windows. Performance. The Navigation PerformanceNavigation returns The contents of the object.

And Navigation Timing Level 1 in through the window. The performance. The Timing acquisition PerformanceTiming object contains a description of the document properties of the data is described by the following objects:

  • Navigation Timing Level 2 PerformanceNavigationTiming object definition
  • The Resource Timing Level 2 PerformanceResourceTiming object definition
  • Performance Timeline Level 2 PerformanceEntry object defined

We can use the Resource Timing Level 2 standards defined in the API Windows. Performance. The getEntriesByType (” Resource “) the length of time required to a particular Resource.

Thus, Navigation Timing Level 2, a new time line is given, and the Navigation Timing Level 1 different description resource load time is to use PerformanceResourceTiming object wrapped up.

https://www.w3.org/TR/navigation-timing-2/timestamp-diagram.svg

NavigationType is an enumeration type that contains four values: Navigate, Reload, back_forward, and prerender now let’s understand where these changes are in the Level 2 standard. the definition of Performance interface was moved to [PERFORMANCE-TIMELINE-2];

The Performance object is defined in the performance-Timeline-2 standard

builds on top of [RESOURCE-TIMING-2];

Based on the RESOURCE – TIMING – 2 standard, from the above you can see in the RESOURCE – TIMING – 2 was used to define PerformanceResourceTiming


support for [PERFORMANCE-TIMELINE-2];

PerformanceEntry objects defined by Performance Timeline Level 2 are used


support for [HR-TIME-2];

All Time values are calculated with timeOrigin defined in High Resolution Time Level 2 as the Time starting point.


support for prerender navigations [RESOURCE-HINTS];

The navigation types defined in Level 1 have three values: 0, 1, 2; Navigate, reload, and back_forward correspond to NavigationType in Level 2. But Level 2 adds a prerender type, and navigation that can be initialized as a PRERender type is defined in the Resource-Hints standard.


exposes number of redirects since the last non-redirect navigation;

RedirectCount field in PerformanceNavigationTiming object


exposes next hop network protocol;

NextHopProtocol field in PerformanceResourceTiming object


exposes transfer, encoded body and decoded body size information;

The transferSize, encodedBodySize, decodedBodySize PerformanceResourceTiming object


secureConnectionStart attribute is now mandatory.

The secureConnectionStart property is optional at Level 1, but must be set by the browser at Level 2

Ok, so you know what this specification defines, and why it’s called Navigation Timeline? Because the specification defines the description document in the process of the whole navigation performance metrics PerformanceNavigationTiming object.

Paint Timing

This specification defines an API to record performance measurements at key points during page loading, such as First Paint, First Contentful Paint.

There is only one version of this specification, and this is the first and latest version, which is still in the Working Draft stage.

  • Paint Timing (WD) ✔︎

This specification contains the following:

  • PerformancePaintTiming object

Performance metrics used to describe some of the key points in time during page loading can be viewed on the console with the following statement:

performance.getEntriesByType('paint');
Copy the code

The result returns an array with each entry of PerformancePaintTiming type, one first-paint and the other first-contentful-paint.

  • 2. Put forward some definitions of key time points, such as First Paint, First Contentful Paint

First Paint, the time from navigation until the browser renders the First pixel to the screen, does not include default background painting, but does include non-default background painting. This is the first critical moment when developers care about page loading — when the browser starts rendering the page. First Contentful Paint (FCP) provides the user with the First feedback that the page actually loads when the browser renders the First content from the DOM. This is the first time users start using page content.

Now that you know what this specification defines, you can see why it is called Paint Timing. Because the specification defines an API to get performance data for Paint at a critical point in time.

User Timing

This specification defines an API that allows Web developers to measure performance. There are currently two versions available. Level 2 is officially released, and Level 3 is still in the draft stage and will replace Level 2 in the future.

Level 3 has been modified from Level 2. The following describes the contents of the Level 3 specification.

  • 1,PerformanceObject adds several methods

    • mark()
    • clearMarks()
    • measure()
    • clearMeasures()

Using the mark() method, you can add a timestamp at the specified location to record the time when it was executed to that location. Mark means tag and will give the tag a name. The measure() method measures the interval between two points in time and gives it a name.

However, there are differences in the use of mark() and measure() in Level 2 and Level 3.

In Level 2, the startTime returned by the mark() method is the time until this marked statement is executed.

// Level 2
performance.mark("mySetTimeout-start");

performance.measure(
  "mySetTimeout"."mySetTimeout-start"."mySetTimeout-end"
);
Copy the code

In Level 3, mark() supports the second argument passed in as an object whose startTime field supports user-defined startTime of the tag and provides a detail field to describe other information to the user. The measure() method also receives the second parameter as an object and provides a detail field to describe other information to the user in addition to the start time and end time of the measurement represented by the second and third parameters in Level 2.

// Level 3
performance.mark("mySetTimeout-start", {
  detail: {component: 'component_name'},
  // In Level 2, startTime does not need to be passed in. The background default is the mark time
  startTime: 123  
});

performance.measure("click_to_update_component", {
    detail: {component: 'component_name'},
    start: startMark.startTime,
    end: performance.now(),
 });
Copy the code
  • PerformanceMark: PerformanceMark

Describe mark () method returns the data, which can be through the performance. GetEntriesByType (‘ mark ‘), the specific meaning of the field can see here: Performance. Mark () | MDN, of which the detail field is at Level 3 defined in the specification.


  • PerformanceMeasure object is defined

Describe the measure () method returns the data, the performance. The getEntriesByType (‘ measure ‘), the specific meaning of the field can be found in the performance. The measure () | MDN view, The detail field is defined in the Level 3 specification.

Ok, now you know why this specification is called User Timing? Because it provides an interface that allows users to customize time nodes to measure performance, as opposed to Resource Timing, Navigation Timing, and Paint Timing which are determined by the browser (e.g. RedirectStart, domainLookupStart, connectEnd, etc.).

Server Timing

We know that the Resource Timing, Navigation Timing, Paint Timing, and User Timing specifications described in the previous sections describe the performance characteristics of Web applications, such as the time at which requests are started, negotiated connections, and received responses. These performance metrics can be captured by the browser, but not how requests are routed, where time is spent on the server, and so on.

This specification describes how server-side performance metrics during the request-response cycle are passed to user agents and defines an API that enables applications to collect, process, and execute these metrics. There is only one version of this specification, currently in the Working Draft stage.

  • Configure Server Timing (WD) ✔︎

This specification contains the following:

  • 1. Defines the communication protocol with the Server: server-timing response header

The response header information is available at www.w3.org/TR/server-t… View the meaning of the response header

> GET /resource HTTP/1.1 > Host: example.com < HTTP/1.1 200 OK < server-timing: miss, db; dur=53, app; Dur =47.2 < server-timing: customView, DC; desc=atl < Server-Timing: cache; desc="Cache Read"; Dur = Trailer: server-timing < (... snip response body ...) < Server-Timing: total; Dur = 123.4Copy the code
  • PerformanceServerTiming. PerformanceServerTiming. PerformanceServerTiming

The browser uses the ServerTiming Header parsing algorithm to represent each parsed performance metric as a PerformanceServerTiming object.

PerformanceServerTiming Each PerformanceServerTiming describes a performance measurement for the server. These PerformanceServerTiming objects are placed in an array, Hung on serverTiming PerformanceResourceTiming object attributes, we can be obtained by the following statement:

performance.getEntriesByType('navigation');
performance.getEntriesByType('resource');
Copy the code

Now that you know what this specification defines, you can see why this specification is called Server Timing. This specification defines an API for capturing the performance of each node on the server.

Long Tasks API

When a user interacts with a page, both the application and the browser queue various events subsequently executed by the browser; for example, the user agent schedules input events based on the user’s activity, and the application schedules callbacks for requestAnimationFrame and other callbacks. Once queued, these events are scheduled by the browser to be queued and executed one by one. However, some tasks can take a long time, and if that happens, the UI thread will be locked and all other tasks will be blocked. To the user, it’s a page that’s stuck, and the browser’s inability to respond to user input is now a major source of bad user experience on the Web. This specification defines an API that can be used to detect the presence of these “Long tasks,” which monopolize the UI thread for Long periods of time and prevent the execution of other critical tasks, such as responding to user input. There is only one version of this specification at present, in the Working Draft stage.

  • Long Tasks API 1 (WD) ✔︎

This specification contains the following:

  • 1, defines the PerformanceLongTaskTiming object

Used to describe the Long Task information, the meaning of each field in object can be in Long | MDN Tasks API reference.

  • 2. What is Long Task

A Long Task is an event loop Task that exceeds 50ms.

Response: Process Events in Under 50ms(switch to English version).

How do I check if there is a Long Task? We can use the PerformanceObserver API.

var observer = new PerformanceObserver(function(list) {
    var perfEntries = list.getEntries();
    for (var i = 0; i < perfEntries.length; i++) {
        // Process long task notifications:
        // report back for analytics and monitoring
        // ...}});// register observer for long task notifications
observer.observe({entryTypes: ["longtask"]});
// Long script execution after this will result in queueing
// and receiving "longtask" entries in the observer.
Copy the code

Okay, now that you know what this specification defines, it’s clear why this specification is called the Long Task API. This specification defines an API for detecting Long tasks.

Optimization strategy

In addition to the above standards for performance measures, the Web Performance Working Group has developed performance tuning standards that browsers can implement and provided us with apis to use these tuning measures.

Resource Hints – Load performance

Many Web applications already utilize a variety of prefetch techniques to improve load performance, including, but not limited to, the use of XMLHttpRequest to fetch and cache resources before they are needed. However, these implementations do not provide the same level of performance that browsers support. To make matters worse, these implementations sometimes conflict with browser logic, leading to delayed or unnecessary resource retrieval that can degrade overall page performance. This specification defines rel attribute values for HTML elements, including DNS-Prefetch, preconnect, prefetch, and PRERender. We can use these resource prompts to have user agents help us pre-resolve DNS, pre-link, pre-load resources, and pre-process resources to improve page performance. There is currently only one version of this specification, which is still in the working draft stage.

  • Resource Hints  Working Draft

Here are the four resource tips defined by this specification:

Dns-prefetch (Resource Hints: dns-prefetch)

Prompt the browser to perform DNS lookups in the background to improve performance.

<link rel="dns-prefetch" href="//example.com">
Copy the code

Resource Hints: PreConnect

Prompt the browser to start the connection handshake (DNS, TCP, TLS) in the background to improve performance.

<link rel="preconnect" href="//example.com">
<link rel="preconnect" href="//cdn.example.com" crossorigin>
Copy the code

Resource Hints: Prefetch

tells the browser to fetch the resources it may need for the next navigation. In most cases, this means that resources will be fetched at a very low priority (because the browser knows that everything we need on the current page is more important than what we think we need on the next page). This means that Prefetch’s primary use is to speed up the next navigation, not the current one.

<link rel="prefetch" href="//example.com/next-page.html" as="document" crossorigin="use-credentials">
<link rel="prefetch" href="/library.js" as="script">
Copy the code

Prefetch has 3 rules:

  • The user agent does not preprocess the resource after it is retrieved and does not use the resource on the current page.
  • The AS property is an optional property, as defined in [PRELOAD].
  • The Crossorigin CORS setting property is an optional property that indicates the CORS policy for the specified resource.


4. Resource Hints: Prerender

Provides prompts to the browser to render the specified page in the background, which speeds up page loading if the user navigates to the page. Used to get the next possible HTML navigation and preprocess the HTML response (that is, the pre-rendered page) by getting the necessary child resources and executing them.

<link rel="prerender" href="//example.com/next-page.html">
Copy the code

If the HTML does not require preprocessing, you can use prefetch resource prompts.

Preload – Load performance

Many applications require fine-grained control over when resources are fetched, processed, and applied to documents. For example, an application may delay the loading and processing of certain resources to reduce resource contention and improve the performance of the initial load. This behavior is typically achieved by moving resource acquisition into the application’s custom resource loading logic, that is, resource acquisition is initiated either with an injected element or with XMLHttpRequest when certain criteria are met. However, there are cases where some resources need to be captured early, but their processing and execution logic depends on specific requirements, such as dependency management, conditional loading, sorting assurance, and so on. This specification defines preload resource hints that can be used with the Link element to tell user agents to preread resources without having to execute them, allowing separation of resource loading from execution, and fine-grained control of when and how resources are loaded.

For example, an application can use the preload keyword to initiate early, high-priority, and non-rendering blocking fetches of CSS resources, and the application can then apply these fetches at appropriate times:

Using markup
<! -- preload stylesheet resource via declarative markup -->
<link rel="preload" href="/styles/other.css" as="style">

<! -- or, preload stylesheet resource via JavaScript -->
<script>
var res = document.createElement("link");
res.rel = "preload";
res.as = "style";
res.href = "styles/other.css";
document.head.appendChild(res);
</script>

Using HTTP Header
Link: <https://example.com/other/styles.css>; rel=preload; as=style
Copy the code

As shown in the previous example, resources can be scheduled through declarative tags, Link HTTP headers ([RFC5988]), or through JavaScript. For more practical examples of how and where to use Preload, see the Use Cases section. Prefetch and preload can both declare a resource and its fetch properties, but differ in how and when the user agent fetches the resource: Prefetch is optional and is typically used for low-priority fetching of resources that may be used for subsequent navigation; Preload is a forced acquisition of resources necessary for the current navigation. Developers should use them wisely to minimize contention and optimize load performance. In addition, the AS attribute in Preload is required to ensure the correct priority, request match, request corresponding to the correct Content-security-policy directive, and send the correct Accept header based on the resource type. Preload: What Is It Good For? by Yoav Weiss

Page Visibility – Saves resources

This specification provides an API for observing the visibility state of a page, such as when a user minimizes a window or switches to another TAB, the API sends a VisiBilityChange event to let listeners know that the page state has changed, and we can detect the event and perform some actions. For example, the site has the image rotation effect, only when the user watches the rotation, will automatically show the next slide; Applications that display information dashboards do not want to poll the server for updates when the page is not visible. Therefore, the page visibility API is particularly useful for saving resources and improving performance by keeping pages from performing unnecessary tasks when documents are not visible. There are currently two versions of this specification. Level 2 will replace Second Edition in the Proposed Recommendation stage.

  • Page Visibility (Second Edition) (REC)
  • Page Visibility Level 2 (PR) configure ︎

The Level 2 specification contains the following:

  • 1. Defines an enumeration of page states: VisibilityState

This enumeration object is not used by us, but is used by browsers.

We can access the page visible state through Document. hidden and Document. visibilityState.

For historical reasons, support for the Hidden property is retained. Developers should use visibilityState whenever possible, and the value returned by Document. visibilityState is defined in the visibilityState enumeration.


var videoElement = document.getElementById("videoElement");

// Autoplay the video if application is visible
if (document.visibilityState == "visible") {
  videoElement.play();
}

// Handle page visibility change events
function handleVisibilityChange() {
  if (document.visibilityState == "hidden") {
    videoElement.pause();
  } else{ videoElement.play(); }}document.addEventListener('visibilitychange', handleVisibilityChange, false);
Copy the code

But the specification is not the same as the way of realization of each major browser vendors, compatibility problems in implementation needs to be done, specific compatibility mode can in Page Visibility API | MDN view.

RequestIdleCallback API – Make full use of resources

This specification defines the Background task cooperative API, provided by the user agent to determine the ability of automatic queue Tasks in my spare time, in the Background Tasks API | MDN in detail.

  • Cooperative Scheduling of Background Tasks (PR) ➤ ︎

The specification name is Cooperative Scheduling of Background Tasks, not requestIdleCallback.

This specification contains the following:

We can use requestIdleCallback() to run high-time, low-priority tasks when the browser is idle.

  • 2. IdleDeadline object is defined

As can be explained by this example in the specification, the requestIdleCallback method receives a function (a task that needs to be executed in idle time) refinePi, whose deadline argument is of type IdleDeadline, This object provides a timeRemaining() function to retrieve the free time available to the task.

function refinePi(deadline) {
  while (deadline.timeRemaining() > 0) {
    if (piStep())
      pointsInside++;
    pointsTotal++;
  }
  currentEstimate = (4 * pointsInside / pointsTotal);
  textElement = document.getElementById("piEstimate");
  textElement.innerHTML="Pi Estimate: " + currentEstimate;
  requestId = window.requestIdleCallback(refinePi);
}
function start() {
  requestId = window.requestIdleCallback(refinePi);
}
Copy the code

Idle callback should not overspend as far as possible, the time allocated on how to make full use of idle callback, here are some Suggestions, but more it is recommended that you go to Background Tasks API | MDN to check the details.

  • Use idle callbacks for non-high priority tasks.
  • Idle callbacks should be allocated as little time as possible.
  • Avoid DOM changes in idle callbacks.
  • Avoid tasks with unpredictable running times.
  • Use timeout when you need it, but only use it when you need it.


Beacon – Data reporting

Often we need to try to report performance data to a Web service before unloading a document. Sending data too early may result in missed data collection opportunities. However, ensuring that data is sent during document unload has been a challenge for developers because user agents often ignore the asynchronous XMLHttpRequest generated in the UNLOAD event handler. To solve this problem, you typically initiate a synchronous XMLHttpRequest** ** in the UNLOAD or beforeUnload event handler to send the data. Synchronous XMLHttpRequest forces the user agent to delay unloading the document, making the next navigation appear later, and the next page can do nothing about poor load performance. This specification adds a way for navigator to use the navigator.sendBeacon() method to send the user agent asynchronously to the server when the opportunity presents itself, without delaying the unloading of the page or affecting the loading performance of the next navigation.

  • Beacon (CR)

Usage:

window.addEventListener('unload', logData, false);

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

For compatibility reasons, you should use another method to send numbers, such as synchronous XMLHttpRequest, when the browser does not support navigator.sendbeacon.

summary

This article introduces the Performance standards developed by the Web Performance Working Group, including Performance metrics and optimization strategies, summarized with a mind map.

Refer to the W3C documentation for more details on Web performance standards. In the next section, I’ll describe where the various performance metrics come from, their definitions, differences, and how they are measured.

thinking

Two questions for today:

  • 1, why Frame Timing | W3C has been moved to Frame Timing | WICG, browser vendors is not possible? If you were to calculate the FPS of a page, how would you do that?

  • 2, The relationship between Resource Hints and Preload, why is Preload not in Resource Hints standard? Do they have a story?

Feel free to discuss in the comments section.


Series of articles

  • preface
  • What is Web Performance?
  • Why care about Web performance?
  • Web performance optimization history
  • W3C and Web Performance Working Group
  • Performance criteria
  • Performance indicators
  • Page rendering process
  • Optimization strategy
    • Load performance
    • Rendering performance
  • To optimize the practice
    • How do I troubleshoot loading performance problems?
    • How do I troubleshoot rendering performance issues?
  • Performance testing tool
  • Performance non-degradation mechanism
  • explore
    • Performance optimization and artificial intelligence
    • The effect of image size on memory, FPS and CPU