In-depth analysis of web page loading performance: Detailed explanation of Navigation Timing API
Core points
- Navigation Timing API provides detailed timing information during web page loading, including DNS lookup, TCP connection establishment, page redirection, DOM construction time and other indicators. It is built into the browser and has no additional overhead.
- Currently, the Navigation Timing API only supports Internet Explorer 9, Firefox, and Chrome. Therefore, browser support should be detected before using the API. The API is defined in the
window.performance.timing
object.
The - API records the timestamps of many milestone events during the page loading process, each event is stored as a property of the
window.performance.timing
object. If an event does not occur, its value is zero. The API also defines an interface that determines how users access specific pages. - Navigation Timing API can be used in conjunction with Ajax calls to report actual user data back to the server. This allows developers to understand how the page behaves in a real environment. This data can also be used to create visual charts for the page loading process.
Web page loading speed is one of the key factors that affect user experience. Slow loading speeds can frustrate users and churn. However, troubleshooting the causes of slow loading is usually not easy, as many factors affect the overall loading time, such as the user's browser, network conditions, server load and application code, etc. Fortunately, the Navigation Timing API can easily help us solve this problem.
In the past, developers had very limited access to data collected in these areas. Many developers have long used JavaScript's Date
objects to collect performance data. For example, the following code measures the loading time by comparing the timestamp after the page load event handler call:
var start = new Date(); window.addEventListener("load", function() { var elapsed = (new Date()).getTime() - start.getTime(); }, false);
There are several problems with this method: first, the time accuracy of JavaScript is notoriously not high; second, using Date
objects will introduce overhead and confusing application code; third, Date
objects can only measure the code in The execution time after running in the browser cannot provide data about the page loading process such as server, network, etc.
Navigation Timing API debut
To provide more accurate and comprehensive page loading data, W3C proposed the Navigation Timing API. This API provides more detailed timing information during page loading. Unlike Date
objects, the Navigation Timing API provides measurement data related to DNS lookup, TCP connection establishment, page redirection, DOM build time, and various other metrics. Navigation Timing is also built into the browser, which means no additional overhead is incurred.
Detection browser support
Currently, the Navigation Timing API only supports Internet Explorer 9, Firefox, and Chrome. Therefore, browser support should be detected before using the API. The API is defined in the window.performance.timing
object. The following functions detect whether the API is supported:
var start = new Date(); window.addEventListener("load", function() { var elapsed = (new Date()).getTime() - start.getTime(); }, false);
Recorded Events
API records the timestamps of many milestone events during page loading. Each event is stored as an attribute of the window.performance.timing
object. The following list describes each event. If an event does not occur (such as page redirection), its value is zero. (Note: Mozilla claims that these events occur in this order.)
navigationStart
: The time after the browser completes the prompt to uninstall the previous document. If there is no previous document,navigationStart
is equal tofetchStart
. This is the beginning of the page loading time that the user perceives.fetchStart
: The moment before the browser starts looking for URLs. The search process involves checking the application cache, or requesting files from the server if it is not cached.domainLookupStart
: The moment before the browser starts to search the URL DNS. If DNS lookup is not required, the value is the same asfetchStart
.domainLookupEnd
: The instant time after the DNS search is completed. If DNS lookup is not required, the value is the same asfetchStart
.connectStart
: The moment the browser connects to the server. If the URL is cached or local resource, the value is equal todomainLookupEnd
.connectEnd
: The instant time after establishing a connection with the server. If the URL is cached or local resource, the value is the same asdomainLookupEnd
.secureConnectionStart
: If using the HTTPS protocol,secureConnectionStart
sets the instant time before the start of the secure handshake. If the browser does not support HTTPS, this value should beundefined
.requestStart
: The instant time before the browser sends the URL request. API undefinedrequestEnd
value.redirectStart
: The start time of the URL fetch that initiates redirection.redirectEnd
: If any redirects exist,redirectEnd
represents the time after the last byte of the last redirect response received.responseStart
: The instant time after the browser receives the first byte of the response.responseEnd
: The instant time after the browser receives the last byte of the response.unloadEventStart
: The instant time before theunload
event of the previous document was triggered. This value is zero if there is no previous document, or if the previous document comes from a different source.unloadEventEnd
: The instant time after theunload
event of the previous document is triggered. This value is zero if there is no previous document, or if the previous document comes from a different source. If there is any redirection to a different source, bothunloadEventStart
andunloadEventEnd
are zero.domLoading
:document.readyState
The instant time before the value is set to "loading".domInteractive
:document.readyState
The instant time before the value is set to "interactive".domContentLoadedEventStart
: The instant time before the DOMContentLoaded event is triggered.domContentLoadedEventEnd
: The instant time after the DOMContentLoaded event is triggered.domComplete
:document.readyState
The instant time before the value is set to "complete".loadEventStart
: The instant time before the load event of the window is triggered. If the event has not been fired, the value is zero.loadEventEnd
: The instant time after the load event of the window is triggered. If the event has not been fired or is still running, the value is zero.
Navigation Type
Navigation Timing API also defines an interface to determine how users access specific pages. The window.performance
object also contains a navigation
object that contains two properties - type
and redirectCount
. The type
property provides a way for the user to navigate to the current page. The following list describes the values ??that are saved by type
:
- If the user navigates to the page by typing a URL, clicking a link, submitting a form, or using scripting actions, the value of
type
is 0. - If the user reloads/refreshs the page,
type
is equal to 1. - If the user navigates to the page through the history (back or forward button),
type
equals 2. - For any other case,
type
equals 255.
redirectCount
Properties contain the number of redirects that have been navigated to the current page. If no redirect occurs, or if any redirects come from a different source, redirectCount
is zero. The following example shows how to access navigation data:
var start = new Date(); window.addEventListener("load", function() { var elapsed = (new Date()).getTime() - start.getTime(); }, false);
Data Interpretation
Navigation Timing API can be used to calculate certain components of page loading time. For example, the time it takes to perform a DNS lookup can be calculated by subtracting timing.domainLookupEnd
from timing.domainLookupStart
. The following example calculates several useful metrics. "userTime" corresponds to the total page loading delay of the user experience. The "dns" and "connection" variables represent the time it takes to perform DNS lookups and connect to the server, respectively. "requestTime" stores the total time sent to the server and received the response. Finally, "fetchTime" stores the total time to complete document acquisition (including access to any cache, etc.). Note that the setTimeout()
function is called in the window load event handler. This ensures that navigation timing data is used only the moment the loading event is completed. If the timing data is accessed from the load event handler, the value of timing.loadEventEnd
will be zero.
function supportsNavigationTiming() { return !!(window.performance && window.performance.timing); }
Navigation Timing API can be used in conjunction with Ajax calls to report actual user data back to the server. This is useful because it allows developers to understand how the page behaves in a real environment. This data can also be used to create visual charts for the page loading process. In fact, Google Analytics has included navigation timing data in its reports.
Key points to remember
- JavaScript's
Date
object cannot accurately measure page load data because it does not know the request before running in the browser. - Navigation Timing API is built into the browser and provides more detailed timing measurements.
- The API also tracks how users navigate to pages.
- Navigation timing data can be sent to the server for analysis.
(The FAQ section about the Navigation Timing API can be added here, and the content can be extracted and rewritten from the original document as needed)
The above is the detailed content of Profiling Page Loads with the Navigation Timing API. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Java and JavaScript are different programming languages, each suitable for different application scenarios. Java is used for large enterprise and mobile application development, while JavaScript is mainly used for web page development.

JavaScriptcommentsareessentialformaintaining,reading,andguidingcodeexecution.1)Single-linecommentsareusedforquickexplanations.2)Multi-linecommentsexplaincomplexlogicorprovidedetaileddocumentation.3)Inlinecommentsclarifyspecificpartsofcode.Bestpractic

The following points should be noted when processing dates and time in JavaScript: 1. There are many ways to create Date objects. It is recommended to use ISO format strings to ensure compatibility; 2. Get and set time information can be obtained and set methods, and note that the month starts from 0; 3. Manually formatting dates requires strings, and third-party libraries can also be used; 4. It is recommended to use libraries that support time zones, such as Luxon. Mastering these key points can effectively avoid common mistakes.

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

JavaScriptispreferredforwebdevelopment,whileJavaisbetterforlarge-scalebackendsystemsandAndroidapps.1)JavaScriptexcelsincreatinginteractivewebexperienceswithitsdynamicnatureandDOMmanipulation.2)Javaoffersstrongtypingandobject-orientedfeatures,idealfor

Event capture and bubble are two stages of event propagation in DOM. Capture is from the top layer to the target element, and bubble is from the target element to the top layer. 1. Event capture is implemented by setting the useCapture parameter of addEventListener to true; 2. Event bubble is the default behavior, useCapture is set to false or omitted; 3. Event propagation can be used to prevent event propagation; 4. Event bubbling supports event delegation to improve dynamic content processing efficiency; 5. Capture can be used to intercept events in advance, such as logging or error processing. Understanding these two phases helps to accurately control the timing and how JavaScript responds to user operations.

JavaScripthassevenfundamentaldatatypes:number,string,boolean,undefined,null,object,andsymbol.1)Numbersuseadouble-precisionformat,usefulforwidevaluerangesbutbecautiouswithfloating-pointarithmetic.2)Stringsareimmutable,useefficientconcatenationmethodsf

If JavaScript applications load slowly and have poor performance, the problem is that the payload is too large. Solutions include: 1. Use code splitting (CodeSplitting), split the large bundle into multiple small files through React.lazy() or build tools, and load it as needed to reduce the first download; 2. Remove unused code (TreeShaking), use the ES6 module mechanism to clear "dead code" to ensure that the introduced libraries support this feature; 3. Compress and merge resource files, enable Gzip/Brotli and Terser to compress JS, reasonably merge files and optimize static resources; 4. Replace heavy-duty dependencies and choose lightweight libraries such as day.js and fetch
