El Protocol que va canviar el Debugging:

Chrome DevTools MCP

i Agents d'IA per a

Web Performance

Photo by Igor Omilaev on Unsplash

El Protocol que va canviar el Debugging:

Chrome DevTools MCP

i Agents d'IA per a

Web Performance

Photo by Igor Omilaev on Unsplash

Performance

Product

Web

Core Web Vitals

El Protocol que va canviar el Debugging:

Chrome DevTools MCP

i Agents d'IA per a

Web Performance

Photo by Igor Omilaev on Unsplash

Chrome DevTools

El Protocol que va canviar el Debugging:

Chrome DevTools MCP

i Agents d'IA per a

Web Performance

Photo by Igor Omilaev on Unsplash

Intel·ligència Artificial

# Exported Chat from Chrome DevTools AI Assistance

**Export Timestamp (UTC):** 2025-11-14T19:10:28.134Z

---

## User

Quin és el valor LCP d'aquest lloc web?

## AI

### Analyzing trace

**Trace:**
````
URL: https://web.dev/learn/performance
Trace bounds: {min: 31194576770, max: 31200204281}
CPU throttling: none
Network throttling: none

# Available insight sets

The following is a list of insight sets. An insight set covers a specific part of the trace, split by navigations. The insights within each insight set are specific to that part of the trace. Be sure to consider the insight set id and bounds when calling functions. If no specific insight set or navigation is mentioned, assume the user is referring to the first one.

## insight set id: NAVIGATION_0

URL: https://web.dev/learn/performance
Bounds: {min: 31194581916, max: 31200204281}
Metrics (lab / observed):
  - LCP: 587 ms, event: (eventKey: r-12198, ts: 31195168852), nodeId: 93
  - LCP breakdown:
    - TTFB: 416 ms, bounds: {min: 31194581916, max: 31194998154.000004}
    - Render delay: 171 ms, bounds: {min: 31194998154.000004, max: 31195168852}
  - CLS: 0.11, event: (eventKey: s--1, ts: 31195069639)
Metrics (field / real users):
  - LCP: 3508 ms (scope: url)
  - INP: 69 ms (scope: url)
  - CLS: 0.44 (scope: url)
  - The above data is from CrUX–Chrome User Experience Report. It's how the page performs for real users.
  - The values shown above are the p75 measure of all real Chrome users
  - The scope indicates if the data came from the entire origin, or a specific url
  - Lab metrics describe how this specific page load performed, while field metrics are an aggregation of results from real-world users. Best practice is to prioritize metrics that are bad in field data. Lab metrics may be better or worse than fields metrics depending on the developer's machine, network, or the actions performed while tracing.
Available insights:
  - insight name: RenderBlocking
    description: Requests are blocking the page's initial render, which may delay LCP. [Deferring or inlining](https://developer.chrome.com/docs/performance/insights/render-blocking) can move these network requests out of the critical path.
    relevant trace bounds: {min: 31195001816, max: 31195047759}
    estimated metric savings: FCP 249 ms, LCP 249 ms
    example question: Show me the most impactful render blocking requests that I should focus on
    example question: How can I reduce the number of render blocking requests?
  - insight name: LCPBreakdown
    description: Each [subpart has specific improvement strategies](https://developer.chrome.com/docs/performance/insights/lcp-breakdown). Ideally, most of the LCP time should be spent on loading the resources, not within delays.
    relevant trace bounds: {min: 31194581916, max: 31195168852}
    example question: Help me optimize my LCP score
    example question: Which LCP phase was most problematic?
    example question: What can I do to reduce the LCP time for this page load?
  - insight name: CLSCulprits
    description: Layout shifts occur when elements move absent any user interaction. [Investigate the causes of layout shifts](https://developer.chrome.com/docs/performance/insights/cls-culprit), such as elements being added, removed, or their fonts changing as the page loads.
    relevant trace bounds: {min: 31195069639, max: 31197062030}
    example question: Help me optimize my CLS score
    example question: How can I prevent layout shifts on this page?
  - insight name: NetworkDependencyTree
    description: [Avoid chaining critical requests](https://developer.chrome.com/docs/performance/insights/network-dependency-tree) by reducing the length of chains, reducing the download size of resources, or deferring the download of unnecessary resources to improve page load.
    relevant trace bounds: {min: 31194583577, max: 31195066632}
    example question: How do I optimize my network dependency tree?
  - insight name: ThirdParties
    description: 3rd party code can significantly impact load performance. [Reduce and defer loading of 3rd party code](https://developer.chrome.com/docs/performance/insights/third-parties) to prioritize your page's content.
    relevant trace bounds: {min: 31195001816, max: 31196455795}
    example question: Which third parties are having the largest impact on my page performance?
````

### Answer

El valor de LCP (Largest Contentful Paint) per a aquesta càrrega de pàgina és de 587 ms. L'element LCP és [LCP element](#node-93).

## User

Com el podem millorar?

## AI

### Answer

El LCP (Largest Contentful Paint) d'aquesta pàgina és de 587 ms. L'element LCP és [LCP element](#node-93).

Per millorar-lo, ens centrarem en les fases del LCP:

### Desglossament del LCP:

*   **Temps fins al primer byte (TTFB)**: 416 ms
*   **Retard de renderització**: 171 ms

Segons el desglossament, el TTFB és la fase que consumeix més temps (416 ms). Per tant, optimitzar el temps de resposta del servidor i la càrrega inicial del document HTML seran els passos més efectius.

### Suggeriments per millorar el LCP:

1.  **Reduir el temps de resposta del servidor (TTFB)**:
    *   **Optimitzar el servidor:** Millora la velocitat amb què el servidor respon a les sol·licituds, per exemple, optimitzant les consultes a la base de dades, utilitzant un CDN (Content Delivery Network) i assegurant-te que el servidor estigui ben aprovisionat.
    *   **Usar serveis de vora (Edge Services) o CDN:** Perquè el contingut estigui més a prop dels usuaris i redueixi la latència. El document principal ([https://web.dev/learn/performance](#s-2372)) va tenir un temps de cua de 2 ms i el primer byte va arribar als 418 ms, indicant que la major part del temps es va passar esperant la resposta del servidor.
2.  **Minimitzar el bloqueig de renderització:**
    *   Els recursos de fulls d'estil CSS bloquejadors de renderització ([https://fonts.googleapis.com/css2?family=Material+Icons&family=Material+Symbols+Outlined&display=block](#s-2528), [https://fonts.googleapis.com/css?family=Google+Sans:400,500|Roboto:400,400italic,500,500italic,700,700italic|Roboto+Mono:400,500,700&display=swap](#s-2521), [https://www.gstatic.com/devrel-devsite/prod/v893b810958a0a119aa54e87c6f4f7fb5af7eacc01ad7a1f488382f3791697b7d/web/css/app.css](#s-2529), [https://web.dev/extras.css](#s-2535)) estan retardant el temps de renderització de la pàgina. Considera la possibilitat d'inline el CSS crític i diferir el CSS no essencial, o carregar-los de forma asíncrona.
3.  **Prioritzar els recursos importants:**
    *   Assegura't que els recursos necessaris per a l'element LCP (l'element [LCP element](#node-93)) es carreguin amb la màxima prioritat possible.
    *   Preconnecta't als orígens que allotgen recursos importants, com ara `fonts.gstatic.com` i `www.gstatic.com`, ja que es descarreguen fonts importants d'aquests dominis.

El Protocol que va canviar el Debugging:

Chrome DevTools MCP

i Agents d'IA per a

Web Performance

Photo by Igor Omilaev on Unsplash

Disclaimer

{
  "mcpServers": {
    "chrome-devtools": {
      "command": "npx",
      "args": ["-y", "chrome-devtools-mcp@latest"]
    }
  }
}

Configuració

gemini mcp add chrome-devtools npx chrome-devtools-mcp@latest

Instal·lació

claude mcp add chrome-devtools npx chrome-devtools-mcp@latest
Check the performance of https://developers.chrome.com

El teu primer prompt

## 🚀 Quick Prompts

These concise prompts work perfectly during presentations:

### 🟢 General Overview

```
Analyze http://localhost:8080 and provide Core Web Vitals scores with their ratings (Good/Needs Improvement/Poor)
```

### 🟢 LCP Quick Analysis

```
What's slowing down LCP on http://localhost:8080? Give me the top 3 fixes with expected improvement
```

### 🟢 CLS Issues

```
Find all layout shifts on http://localhost:8080 and explain how to fix each one
```

### 🟢 Network Problems

```
Analyze the network waterfall on http://localhost:8080 - what's blocking the critical path?
```

### 🟢 Failed Requests

```
Are there any failed requests on http://localhost:8080? What's their performance impact?
```

### 🟢 Before vs After

```
Compare performance between http://localhost:8080 and http://localhost:8081/solutions/index-optimized.html - show improvement percentages
```

### 🟡 INP (Interaction Responsiveness)

```
Measure INP on http://localhost:8080 - which interactions are slowest and why?
```

**Note:** Requires interaction with the page (clicks, typing)

### 🔴 LoAF (Animation Smoothness)

```
Identify long animation frames on http://localhost:8080 during scrolling - what's causing frame drops?
```

**Note:** Requires Chrome 116+ and scrolling on the page.

---

## 📊 Complexity Legend

- 🟢 **BASIC** - Works out-of-the-box, ideal for live demos
- 🟡 **INTERMEDIATE** - Requires prior setup in DevTools (record trace, etc.)
- 🔴 **ADVANCED** - Requires multiple steps or manual configuration

---

## General Analysis

### 🟢 Prompt: Comprehensive Performance Audit

```
Analyze the performance of http://localhost:8080 and provide:
1. LCP value and breakdown by phases (TTFB, resource load, render delay, element render)
2. CLS score and identify all layout shift culprits
3. TBT score and list all long tasks over 50ms
4. Top 3 performance issues prioritized by impact
5. Specific optimization recommendations with expected improvement
```

**Expected Output:**

- Core Web Vitals scores
- Breakdown of each metric
- Prioritized list of issues
- Actionable recommendations

---

## LCP (Largest Contentful Paint)

### 🟡 Prompt: Detailed LCP Analysis

**Prerequisite:** Performance trace recorded (DevTools → Performance → Record → Reload)

```
Start a performance trace on http://localhost:8080 and analyze the LCP element:
1. Identify the LCP element selector and its size
2. Break down LCP into phases with timing for each:
   - TTFB (Time to First Byte)
   - Resource load delay
   - Resource load time
   - Element render delay
3. Check if the LCP resource is render-blocking
4. Analyze the network request for the LCP resource (size, compression, caching)
5. Suggest specific optimizations with expected improvement in milliseconds
```

**What to Look For:**

- Hero image should be the LCP element
- LCP time ~4-5 seconds
- Large resource load time
- Render-blocking resources delaying LCP

### 🟢 Prompt: LCP Resource Optimization

```
For the LCP element on http://localhost:8080:
1. Check if there's a preload link for the LCP resource
2. Verify if the image has proper dimensions (width/height attributes)
3. Check if modern image formats are available (WebP, AVIF)
4. Analyze if the image could be optimized (compression, sizing)
5. Provide code examples for each optimization
```

---

## CLS (Cumulative Layout Shift)

### 🟡 Prompt: Identify CLS Culprits

**Prerequisite:** Performance trace recorded

```
Analyze layout shifts on http://localhost:8080:
1. Record a performance trace
2. Identify ALL elements causing layout shifts
3. For each culprit, check:
   - If images are missing width/height attributes
   - If fonts are causing FOIT (Flash of Invisible Text)
   - If dynamic content is injected without reserved space
   - The exact shift distance and timing
4. Provide CSS fixes for each issue with code examples
```

**Expected Findings:**

- Images without dimensions
- Dynamically injected ad causing shift
- Font loading causing layout shift
- Total CLS score ~0.3

### Prompt: CLS by Element

```
For each layout shift on http://localhost:8080:
1. Identify the element that shifted
2. Calculate the shift distance
3. Determine when the shift occurred (timestamp)
4. Explain WHY the shift happened
5. Provide the exact CSS fix needed
```

---

## TBT/INP (Total Blocking Time / Interaction to Next Paint)

### Prompt: Find Long Tasks

```
Find all JavaScript long tasks on http://localhost:8080:
1. Start performance trace
2. List ALL tasks exceeding 50ms with their duration
3. For each long task, identify:
   - The function/file causing it
   - The call stack
   - Whether it's on page load or user interaction
4. Suggest code splitting or Web Worker strategies
5. Estimate TBT improvement for each fix
```

**Expected Findings:**

- Long tasks from `heavy-blocking.js`
- Long tasks from `third-party-blocking.js`
- Expensive event handlers
- Total TBT ~800ms

### Prompt: Analyze Slow Event Handlers

```
Analyze event handlers on http://localhost:8080:
1. Identify all click, scroll, and input handlers
2. Measure execution time for each
3. Check if handlers use throttling or debouncing
4. Identify forced synchronous layouts (reflows)
5. Provide optimized versions of slow handlers
```

---

## Network Performance

### Prompt: Analyze Network Waterfall

```
Analyze the network waterfall for http://localhost:8080:
1. Get all network requests in loading order
2. Identify render-blocking resources in critical path
3. Check for:
   - Resources without compression (check Content-Encoding header)
   - Missing cache headers (check Cache-Control)
   - Requests in series that could be parallel
   - CORS errors
   - Slow API endpoints (>1s)
4. Provide specific optimization recommendations for the top 5 slowest resources
```

**Expected Findings:**

- No compression enabled
- Cache-Control: no-store on all resources
- Serial CSS loading due to @import
- Slow `/api/slow-data` endpoint (2.5s)

### Prompt: Optimize Critical Path

```
Analyze the critical rendering path on http://localhost:8080:
1. Identify all render-blocking CSS files
2. Identify all parser-blocking JavaScript files
3. Calculate the critical path length
4. Suggest which CSS should be inlined
5. Suggest which JavaScript should be deferred or async
6. Provide the optimized HTML <head> structure
```

### Prompt: Analyze Failed Requests (404, Failed Requests)

```
Analyze failed network requests on http://localhost:8080:
1. Identify all requests that returned 404, 5xx, or failed entirely
2. For each failed request:
   - Show the URL and status code
   - Measure total time spent (including network overhead)
   - Check if it's synchronous (blocking) or asynchronous
   - Identify which script/file initiated the request
3. Calculate total wasted time on failed requests
4. Check if any failed requests are blocking critical resources
5. Identify the impact on Core Web Vitals (especially TBT)
6. Provide recommendations to fix or remove failed requests
```

**Expected Findings:**

- 404 error for `/api/analytics` (from `third-party-blocking.js`)
- Request is **synchronous** (blocks main thread)
- Wasted network time: 50-200ms
- Added to TBT (Total Blocking Time)
- Try-catch silently hides the error from console

**Why This Matters:**
This demonstrates a real-world issue where third-party analytics/tracking scripts make requests to endpoints that no longer exist. Even though they fail, they:

- Waste network bandwidth
- Occupy connection slots
- Block the main thread (if synchronous)
- Are often hidden from developers (silent failures)

**Real-World Examples:**

- Old Google Analytics tracking IDs
- Deprecated Facebook Pixel endpoints
- Removed A/B testing experiments
- CDN URLs that changed after deployment
- Third-party services that shut down

---

## Memory Leaks

### 🔴 Prompt: Detect Memory Leaks

**Prerequisite:** Two heap snapshots taken manually (Memory panel → Take snapshot)

```
Detect memory leaks on http://localhost:8080:
1. Take initial memory snapshot (Heap Snapshot 1)
2. Interact with the page (click buttons, scroll, type in input)
3. Wait 30 seconds
4. Take second memory snapshot (Heap Snapshot 2)
5. Compare snapshots and identify:
   - Detached DOM nodes (look for window.detachedNodes)
   - Event listeners not cleaned up
   - Growing arrays or objects (window.leakedObjects, window.globalDataAccumulator)
   - Closures holding large data
6. For each leak, suggest the fix with code
```

**Expected Findings:**

- Detached DOM nodes accumulating
- Event listeners never removed
- Global arrays growing continuously
- Timers never cleaned up

### Prompt: Analyze Heap Growth

```
Analyze heap growth on http://localhost:8080:
1. Record heap allocations over 60 seconds
2. Identify objects/arrays growing over time
3. Find the allocation stack traces
4. Determine if growth is expected or a leak
5. Provide code to fix the leaks
```

---

## Render Performance

### Prompt: Analyze Rendering Performance

```
Analyze rendering performance on http://localhost:8080:
1. Record a performance trace while scrolling
2. Identify frames that took >16ms (dropped frames)
3. Look for:
   - Forced synchronous layouts
   - Expensive style calculations
   - Excessive paint areas
   - Layout thrashing
4. Provide optimizations for smooth 60fps scrolling
```

---

## Third-Party Scripts

### Prompt: Impact of Third-Party Scripts

```
Analyze third-party scripts impact on http://localhost:8080:
1. Identify all third-party script requests
2. Measure blocking time for each
3. Calculate total impact on:
   - FCP (First Contentful Paint)
   - LCP
   - TBT
4. Suggest loading strategies (defer, async, lazy load)
5. Recommend which scripts could be removed or optimized
```

---

## Comparative Analysis

### Prompt: Before vs After

```
Compare performance between:
- http://localhost:8080/ (bad version)
- http://localhost:8081/solutions/index-optimized.html (optimized version)

Provide:
1. Side-by-side metrics comparison
2. Improvement percentages for each metric
3. Which optimizations had the biggest impact
4. Load time comparison
5. Network transfer size comparison
```

**⚠️ Important:** Both servers must be running:

- Port 8080: Bad version (`npm start`)
- Port 8081: Optimized version (`npm run start:optimized`)
- Or run both: `npm run start:both`

---

## Mobile Performance

### Prompt: Analyze Mobile Performance

```
Analyze http://localhost:8080 with mobile throttling:
1. Apply "Slow 3G" network throttling
2. Apply "4x CPU slowdown"
3. Measure Core Web Vitals
4. Compare with desktop performance
5. Identify mobile-specific issues
6. Provide mobile optimization recommendations
```

---

## Automated Testing Prompts

### Prompt: Performance Budget Check

```
Check performance budgets for http://localhost:8080:
1. Measure current metrics:
   - LCP: should be < 2.5s (Good)
   - INP: should be < 200ms (Good) [Note: FID is deprecated, use INP]
   - CLS: should be < 0.1 (Good)
   - FCP: should be < 1.8s (Good)
   - Total page weight: should be < 2MB (without video/large media)
   - Initial JS bundle: should be < 200KB
   - Number of requests: should be < 50
2. Report which budgets are exceeded
3. Calculate how much improvement is needed
4. Suggest prioritized fixes to meet budgets
```

---

## 💡 Tips for Using These Prompts

### During the Talk:

1.  **Prepare copypasta** - Have the prompts ready to copy
2.  **Use "Quick" versions** - They are faster to type live
3.  **Have backup screenshots** - In case the AI gives unexpected results
4.  **Practice beforehand** - Run the prompts before the talk to know what to expect

### For Best Results:

1.  **Be specific** - Always include the full URL
2.  **Ask for code** - Request code examples for the fixes
3.  **Ask for prioritization** - Ask which issues have the biggest impact
4.  **Iterate** - Start general, then go deeper
5.  **Compare** - Use before/after to validate improvements

### MCP Limitations:

- ⚠️ Results may vary between runs (it's probabilistic AI)
- ⚠️ You need to open DevTools manually
- ⚠️ Some analyses require prior setup (traces, snapshots)
- ⚠️ **Always validate** recommendations against known best practices

Promps

El Protocol que va canviar el Debugging: Chrome DevTools MCP i Agents d'IA per a Web Performance

By Joan León

El Protocol que va canviar el Debugging: Chrome DevTools MCP i Agents d'IA per a Web Performance

  • 23