How to Evaluate Site Speed with the Performance API
source link: https://blog.asayer.io/how-to-evaluate-site-speed-with-the-performance-api
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Browser DevTools are great for monitoring web application performance on your local development PC. However, they’re less practical for measuring site speed on different devices, browsers, and network connections across global locations.
The Performance API records DevTool-like metrics from real users as they navigate your application. You can post collected data to a service such as Asayer.io, e.g.
To help identify performance bottlenecks on specific browsers, devices, or even user sessions.
What is the Performance API?
The Performance API is a collection of APIs used to measure:
- navigation timing — redirects, DNS look-ups, DOM loaded, page loaded, etc.
- resource timing — loading of specific page assets such as CSS, scripts, images, and Ajax calls
- paint timing — the point at which browser rendering starts, and
- user timing — custom measurements for your application, including
performance.now()
Historically, developers had to adopt the Date()
function to record elapsed times, e.g.
but the Performance API is:
- higher resolution. Unlike
Date()
, it records timings in fractions of a millisecond. - more reliable.
Date()
uses the system time so timings can become inaccurate when the OS synchronises the clock.
The API is available in client-side JavaScript in most modern browsers and is detectable with:
Resource and user timing is also available in client-side Web Workers. These provide a way to run long-running or computationally-expensive scripts in the background which do not interfere with the browser’s main processing thread.
User timing APIs are also available in server-side:
- Node.js applications with the
performance_hook
module, and - Deno applications run with the
--allow-hrtime
option.
The Performance API and documentation can be a little difficult to understand partly because it has evolved. I hope the information and examples in this article help illustrate its potential.
Load timing properties
The sections below describe:
Both objects provide the following identification properties:
- name — resource URL
- entryType — performance type (
"navigation"
for a page,"resource"
for a page asset) - initiatorType — resource which initiated the performance entry (
"navigation"
for a page) - serverTiming — an array of PerformanceServerTiming objects with
name
,description
, andduration
metrics written by the server to the HTTPServer-Timing
header
Both objects provide the following timing properties shown here in the chronological order you would expect them to occur. Timestamps are in milliseconds relative to the start of the page load:
- startTime — timestamp when the fetch started (
0
for a page since it’s the first asset loaded) - nextHopProtocol — network protocol used
- workerStart — timestamp before starting a Progressive Web App (PWA) Service Worker (
0
if the request is not intercepted by a Service Worker) - redirectStart — timestamp of the fetch which initiated a redirect
- redirectEnd — timestamp after receiving the last byte of the last redirect response
- fetchStart — timestamp before the resource fetch
- domainLookupStart — timestamp before a DNS lookup
- domainLookupEnd — timestamp after the DNS lookup
- connectStart — timestamp before the browser establishes a server connection
- connectEnd — timestamp after establishing a server connection
- secureConnectionStart — timestamp before the browser starts the SSL handshake process
- requestStart — timestamp before the browser requests the resource
- responseStart — timestamp when the browser receives the first byte of data
- responseEnd — timestamp after receiving the last byte or closing the connection
- duration — the difference between startTime and responseEnd
Both objects provide the following download size properties:
- transferSize — the resource size in bytes (octets), including the header and compressed body
- encodedBodySize — the resource’s payload body in bytes (octets) before decoding/uncompressing
- decodedBodySize — the resource’s payload body in bytes (octets) after decoding/uncompressing
Page PerformanceNavigationTiming
objects provide further metrics about loading and DOM events, although these are not supported in Safari:
- type — either
"navigate"
,"reload"
,"back_forward"
or"prerender"
- redirectCount — the number of redirects
- unloadEventStart — timestamp before the
unload
event of the previous document (zero if no previous document) - unloadEventEnd — timestamp after the
unload
event of the previous document (zero if no previous document) - domInteractive — timestamp before the browser sets the document readiness to interactive when HTML parsing and DOM construction is complete
- domContentLoadedEventStart — timestamp before document’s
DOMContentLoaded
event fires - domContentLoadedEventEnd — timestamp after document’s
DOMContentLoaded
event completes - domComplete — timestamp before the browser sets the document readiness to complete when DOM construction and
DOMContentLoaded
events have completed - loadEventStart — timestamp before the page
load
event has fired - loadEventEnd — timestamp after the page
load
event and all assets are available
Navigation timing
The Navigation Timing API collates timings for unloading the previous page, redirects, DNS lookups, page loading, file sizes, load events, and more. The information would be difficult to reliably determine in any other way.
Navigation timing is available to client-side JavaScript window and Web Worker functions. Pass a "navigation"
type to the performance.getEntriesByType()
:
or the page URL to performance.getEntriesByName()
:
Either option returns an array with a single element containing a PerformanceNavigationTiming
object (see load timing properties). It contains read-only properties about the resource load times, e.g.
You can use it to calculate useful page loading metrics from users, e.g.
Resource timing
You can examine load timings for other resources such as images, stylesheets, scripts, Fetch, and XMLHttpRequest Ajax calls in a similar way to the page.
Resource timing is available to client-side JavaScript window and Web Worker functions. Pass a "resource"
type to the performance.getEntriesByType()
to return an array. Each element is a PerformanceResourceTiming
object (see load timing properties) representing a resource loaded by the page (but not the page itself):
example result:
You can also fetch a resource by passing its exact URL to performance.getEntriesByName()
:
This returns an array with a single element:
You could use this to report to calculate the load times and sizes of each JavaScript resource as well as the total:
The Performance API records at least 150 resource metrics, but you can define a specific number with performance.setResourceTimingBufferSize(N)
, e.g.
You can clear existing metrics with performance.clearResourceTimings()
. This may be practical when you no longer require page resource information but want to record Ajax requests:
Paint timing
The Paint Timing API is available to client-side JavaScript window functions and records two rendering operations observed during page construction.
Pass a "paint"
type to the performance.getEntriesByType()
to return an array containing two PerformancePaintTiming objects:
The result:
where:
first-paint: the browser has painted the first pixel on the page, and
first-contentful-paint: the browser has painted the first item of DOM content, such as text or an image.
Note that "duration"
will always be zero.
performance.now()
performance.now()
returns a high-resolution timestamp in fractions of a millisecond since the beginning of the process’s lifetime. The method is available in client-side JavaScript, Web Workers, Node.js, and Deno.
In client-side JavaScript, the performance.now()
timer starts at zero when the process responsible for creating the document
started. Web Worker, Node.js, and Deno timers start when the script process initially executes.
Note that Node.js scripts must load the Performance hooks (perf_hooks
) module to use the Performance API. In CommonJS:
or as an ES module:
You can use performance.now()
to time scripts, e.g.
A further non-standard timeOrigin
property returns the timestamp at which the current process began. This is measured in Unix time since 1 January 1970 and is available in Node.js and browser JavaScript (not IE or Safari):
User timing
performance.now()
becomes cumbersome when taking more than a couple of timing measurements. The performance.mark()
method adds a named PerformanceMark object object with a timestamp to the performance buffer. It’s available in client-side JavaScript, Web Workers, Node.js, and Deno:
Pass a "mark"
type to the performance.getEntriesByType()
to return an array of marks:
The resulting array contains objects with name
and startTime
properties:
The performance.measure()
method calculates the elapsed time between two marks. It’s passed the measure name, the start mark name (or a falsy value to use the page/script load time), and the end mark name (or a falsy value to use the current time), e.g.
This adds a PerformanceMeasure object to the performance buffer with a calculated duration. Pass a "measure"
type to the performance.getEntriesByType()
to return an array of measures:
The resulting array:
You can also fetch mark and measure entries by name using performance.getEntriesByName()
:
Other useful methods include:
performance.getEntries()
— returns an array of all performance entries including marks, measures, navigation timing, resource timing, and paint timingperformance.clearMarks( [name] )
— clear a named mark, or omit the name to clear all marksperformance.clearMeasures( [name] )
— clear a named measure, or omit the name to clear all measures
Frontend Monitoring
Asayer is a frontend monitoring tool that replays everything your users do and shows how your web app behaves for every issue. It lets you reproduce issues, aggregate JS errors and monitor your web app’s performance.
Happy debugging, for modern frontend teams - Start monitoring your web app for free.
PerformanceObserver
The PerformanceObserver interface can watch for changes to the performance buffer and run a function when specific objects appear. It’s most practically used for mark, measure, and resource loading events (navigation and paint timings will generally occur before a script has started).
First, define an observer function. This could log an event or post the data to a statistics endpoint:
The function has the following parameters:
a
list
of observer entries, andthe
observer
object so it’s possible to disconnect() if necessary.
Pass this function when creating a new PerformanceObserver
object then run the observe()
method with the entryTypes
to observe:
Adding a new mark or measure will now run the performanceObserver()
function and display details about that measurement.
Future performance options
Chrome-based browsers offer a non-standard performance.memory
property which returns a single MemoryInfo object:
where:
- jsHeapSizeLimit — the maximum size of the heap in bytes
- totalJSHeapSize — the total allocated heap size in bytes, and
- usedJSHeapSize — The currently active segment of JS heap in bytes.
The Frame timing API is not implemented in any browser, but will record the amount of browser work in one event loop iteration. This includes processing DOM events, CSS animations, rendering, scrolling, resizing, etc. The API should be able to report potential jerkiness when a frame takes longer than 16.7 milliseconds so updates drop below 60 frames per second.
Finally, the Self-Profiling API is an experimental feature under development in Chrome. Given a sample rate, the API will help locate slow or unnecessary code in a similar way to the DevTools performance report:
Pinpoint performance problems
It’s easy to presume your application runs well when you’re developing on a new PC connected to a fast network. The performance API offers a way to prove — or disprove — performance issues by collecting real user metrics based on their devices, connections, and locations.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK