In browser-based JavaScript, the Performance interface provides access to performance-related information for the current page. It's part of the High Resolution Time API and the Performance Timeline API, which can be used to measure the performance of your web application.
Here are some ways you can measure performance using JavaScript:
- Timing API:
performance.now(): This method returns a high-resolution timestamp measured in milliseconds, accurate to five microseconds. You can use it to measure how long operations take to complete.
let start = performance.now();
// Perform the operation you want to measure
for (let i = 0; i < 1000; i++) {
console.log(i);
}
let end = performance.now();
console.log(`Operation took ${end - start} milliseconds.`);
- User Timing API:
performance.mark(): This function allows you to create a timestamp with a given name that you can reference later.
performance.measure(): This function can be used to create a named timestamp measuring the time between two marks.
performance.mark('startOperation');
// Your operation here
for (let i = 0; i < 1000; i++) {}
performance.mark('endOperation');
performance.measure('operationDuration', 'startOperation', 'endOperation');
// Retrieve the measures
let measures = performance.getEntriesByType('measure');
measures.forEach(measure => console.log(`${measure.name}: ${measure.duration}`));
// Don't forget to clear marks and measures if you're done with them
performance.clearMarks();
performance.clearMeasures();
- Resource Timing API:
- This part of the Performance API allows you to collect detailed information on the loading of various resources such as scripts, stylesheets, images, etc.
window.addEventListener('load', (event) => {
performance.getEntriesByType('resource').forEach((resource) => {
console.log(`Resource: ${resource.name}, Fetch Start: ${resource.fetchStart}, Response End: ${resource.responseEnd}, Duration: ${resource.duration}`);
});
});
-
Performance Timing (Deprecated):
- The
performance.timing property contains a PerformanceTiming object that provides legacy navigation timing information, like how much time it takes to unload the previous page, DNS lookup duration, TCP connection time, etc.
- Note that
performance.timing is deprecated and it's recommended to use the Navigation Timing API.
-
Navigation Timing API:
- Provides timing-related information specifically for navigation and page loads.
window.addEventListener('load', (event) => {
let navigationTiming = performance.getEntriesByType('navigation')[0];
console.log('Time to Interactive:', navigationTiming.domInteractive);
console.log('Total Load Time:', navigationTiming.loadEventEnd - navigationTiming.startTime);
});
When measuring performance using these APIs, it's important to conduct multiple runs and consider the average timing to account for variability due to caching, background processes, and other factors.
Keep in mind this is a basic introduction to the Performance API, and there are more advanced techniques and metrics, like the First Contentful Paint (FCP), Largest Contentful Paint (LCP), Cumulative Layout Shift (CLS), and others that are part of modern performance monitoring practices. Tools like Lighthouse, which is integrated into Chrome DevTools, can help automate the collection of these metrics and offer suggestions for improvements.