---
title: "Web Performance API: Measure What Matters"
description: "From slow to fast: Using JavaScript's Performance API to optimize web apps"
canonical: "https://www.trevorlasn.com/blog/performance-web-api-in-javascript"
author: "Trevor I. Lasn"
published: "2024-11-29"
last-updated: "2026-02-15"
topics: ["Web performance", "JavaScript"]
---

# Web Performance API: Measure What Matters

From slow to fast: Using JavaScript's Performance API to optimize web apps

By Trevor I. Lasn · Published 2024-11-29 · Updated 2026-02-15 · https://www.trevorlasn.com/blog/performance-web-api-in-javascript

Web performance isn't just about fast load times. It's about understanding what happens from the moment a user hits your site until they can actually use it. The Performance API opens up this black box of browser behavior.

[Browser support for `performance` on webstatus.dev](https://webstatus.dev/features/performance)

Speed affects everything. Users leave slow sites. Search engines penalize them. Mobile users get frustrated when apps drain their batteries. [The Performance API](https://developer.mozilla.org/en-US/docs/Web/API/Performance) helps measure these real-world impacts.

```javascript title="JavaScript"
// Basic usage of Performance API
const pageLoad = performance.now();
const navigationTiming = performance.getEntriesByType('navigation')[0];
const paintTiming = performance.getEntriesByType('paint');

console.log(`Page load time: ${pageLoad}ms`);
console.log(`Time to first byte: ${navigationTiming.responseStart}ms`);
console.log(`First paint: ${paintTiming[0].startTime}ms`);
```

While the basic API gives us snapshots, [`PerformanceObserver`](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceObserver) lets us watch performance metrics as they happen:

```javascript title="JavaScript"
// Create an observer for ongoing performance monitoring
const observer = new PerformanceObserver((list) => {
  for (const entry of list.getEntries()) {
    switch(entry.entryType) {
      case 'navigation':
        console.log(`Page loaded in ${entry.loadEventEnd}ms`);
        break;
      
      case 'paint':
        console.log(`${entry.name} at ${entry.startTime}ms`);
        break;
      
      case 'largest-contentful-paint':
        console.log(`Main content visible at ${entry.startTime}ms`);
        break;
      
      case 'layout-shift':
        console.log(`Layout shift score: ${entry.value}`);
        break;
    }
  }
});

// Start observing multiple types of performance entries
observer.observe({
  entryTypes: [
    'navigation',
    'paint',
    'largest-contentful-paint',
    'layout-shift'
  ]
});
```

In practice, we often use both methods together. The direct API calls give us immediate data, while the observer keeps track of ongoing performance:

```javascript title="JavaScript"
class PerformanceTracker {
  constructor() {
    // Get initial timing data
    this.initialLoad = performance.now();
    this.navigationTiming = performance.getEntriesByType('navigation')[0];
    
    // Set up ongoing monitoring
    this.observer = new PerformanceObserver((list) => {
      list.getEntries().forEach(entry => {
        if (this.isSignificantMetric(entry)) {
          this.logMetric(entry);
        }
      });
    });

    // Start observing
    this.observer.observe({
      entryTypes: [
        'navigation',
        'resource',
        'paint',
        'largest-contentful-paint'
      ]
    });
  }

  isSignificantMetric(entry) {
    const significantMetrics = [
      'first-paint',
      'first-contentful-paint',
      'largest-contentful-paint'
    ];
    
    return significantMetrics.includes(entry.name);
  }

  logMetric(entry) {
    const timeSinceLoad = performance.now() - this.initialLoad;
    
    console.log(
      `${entry.name} occurred at ${entry.startTime}ms ` +
      `(${timeSinceLoad}ms since tracking started)`
    );
  }
}

// Start tracking
const tracker = new PerformanceTracker();
```

This combined approach gives us the best of both worlds: immediate access to performance data and ongoing monitoring of key metrics as they occur.

The Performance API is especially useful for monitoring Core Web Vitals - metrics that directly impact user experience.

```javascript title="JavaScript"
// Track Largest Contentful Paint (LCP)
let lcpValue = 0;
const lcpObserver = new PerformanceObserver((list) => {
  const entries = list.getEntries();
  // We only care about the most recent LCP
  const lastEntry = entries[entries.length - 1];
  lcpValue = lastEntry.renderTime || lastEntry.loadTime;
});

lcpObserver.observe({ entryTypes: ['largest-contentful-paint'] });

// Track Interaction to Next Paint (INP)
let inpValue = 0;
new PerformanceObserver((list) => {
  for (const entry of list.getEntries()) {
    if (entry.interactionId) {
      const duration = entry.duration;
      inpValue = Math.max(inpValue, duration);
      console.log(`Interaction duration: ${duration}ms`);
    }
  }
}).observe({ type: 'event', buffered: true, durationThreshold: 16 });

// Track Cumulative Layout Shift (CLS)
let clsValue = 0;
new PerformanceObserver((list) => {
  for (const entry of list.getEntries()) {
    if (!entry.hadRecentInput) {
      clsValue += entry.value;
    }
  }
}).observe({ entryTypes: ['layout-shift'] });
```
<br />

### Resource Loading Performance

Resource loading directly impacts how fast users can interact with your site. Every script, stylesheet, image, and font file adds to the loading time. But it's not just about the total download size - it's about when and how these resources load.

When browsers load resources, they follow specific patterns:

```javascript title="JavaScript"
// Track resource loading performance
const resourceObserver = new PerformanceObserver((list) => {
  list.getEntries().forEach(entry => {
    // Filter out non-critical resources
    if (entry.initiatorType === 'script' || 
        entry.initiatorType === 'css' || 
        entry.initiatorType === 'fetch') {
      
      const timing = {
        name: entry.name,
        type: entry.initiatorType,
        startTime: entry.startTime,
        duration: entry.duration,
        transferSize: entry.transferSize,
        // Time spent waiting for the server
        waitTime: entry.responseStart - entry.requestStart,
        // Time spent downloading
        downloadTime: entry.responseEnd - entry.responseStart
      };

      if (timing.duration > 500) {
        console.warn('Slow resource load:', timing);
      }
    }
  });
});

resourceObserver.observe({ 
  entryTypes: ['resource'],
  buffered: true // Include resources that loaded before observer was created
});
```

The sequence matters. Some resources block rendering entirely until they're loaded (like CSS), while others can load in parallel (like images). Understanding these patterns helps identify optimization opportunities:

```javascript title="JavaScript"
// Identify render-blocking resources and waterfall effects
const waterfall = new PerformanceObserver((list) => {
  const entries = list.getEntries();
  let lastBlockingResource = 0;
  
  entries.forEach(entry => {
    if (entry.renderBlockingStatus === 'blocking') {
      const endTime = entry.startTime + entry.duration;
      lastBlockingResource = Math.max(lastBlockingResource, endTime);
      
      console.log(
        `Blocking resource ${entry.name} delayed rendering by ${entry.duration}ms`
      );
    }
  });
  
  console.log(`Total render blocking time: ${lastBlockingResource}ms`);
});

waterfall.observe({ entryTypes: ['resource'] });
```

By understanding how resources load, you can make informed decisions about:

- Which resources to defer or load asynchronously
- When to inline critical CSS
- How to prioritize resource loading
- Whether to use resource hints like preload and prefetch
- Where to implement code splitting

Performance monitoring isn't just about collecting metrics - it's about using them to make informed decisions. Whether you're debugging a slow page load, optimizing resource delivery, or ensuring a smooth user experience, the Performance API provides the insights needed to make meaningful improvements.

By combining basic timing data with real-time performance observers, we can build comprehensive monitoring systems that help maintain and improve web application performance. The key is choosing the right metrics for your specific use case and setting appropriate thresholds based on your users' needs.
