Chrome DevTools is the "Swiss Army Knife" for modern web development and debugging. Mastering it is essential for web developers and testers alike.
How to Open DevTools:
- Right-Click Inspect: Right-click anywhere on a webpage and select "Inspect."
- Keyboard Shortcut: Windows/Linux:
F12
orCtrl+Shift+I
; macOS:Cmd+Opt+I
. - Browser Menu: Click the three dots menu in the upper right corner of the browser -> More Tools -> Developer Tools.
Part 1: Getting Started with Core Panels
I. Elements Panel: The "X-Ray" for Webpages
In a nutshell: View and edit the page's HTML structure and CSS styles in real-time.
This is your direct interface with the page's visual elements. On the left is the dynamically generated HTML DOM tree, and on the right is the CSS styles pane for the corresponding element. You can edit any HTML or CSS in real-time and see the changes immediately on the page (changes are lost after refresh), making it ideal for quickly validating layout and style adjustments.
II. Console Panel: A Window for Communicating with the Page
In a nutshell: View log messages and an interactive command line for executing JavaScript code.
This is your go-to place for diagnosing JavaScript issues. All console.log
outputs, warnings (yellow), and fatal errors (red) are displayed here. It is also a fully functional JavaScript runtime environment (REPL), where you can execute code, query variables, and directly manipulate page elements.
III. Network Panel: The "Surveillance Camera" for Webpage Loading
In a nutshell: Monitor all network requests and responses during page loading. A powerful tool for performance analysis and API debugging.
It records all resources loaded by the page, including HTML, CSS, JS, images, and API requests (Fetch/XHR) to the server. You can filter requests, view status codes (e.g., 200
for success, 404
for not found), and inspect request headers and response bodies.
- Advanced: Show Preflight Requests When dealing with complex Cross-Origin Resource Sharing (CORS) requests, the browser first sends an
OPTIONS
method "preflight request." DevTools hides it by default. To view it, click the Settings icon (⚙️) in the upper right corner of the Network panel and check "ShowOPTIONS
preflight requests". This is crucial for debugging cross-origin issues.
IV. Application Panel: The Browser's "Local Repository"
In a nutshell: View and manage all local data stored by the browser for the website.
This manages the information that the website stores on your computer, such as Local Storage
(permanent storage), Session Storage
(session storage), and Cookie
(commonly used to maintain login status). You can view, edit, and even clear this data, making it ideal for debugging local storage-related features.
Part 2: Advanced Debugging and Performance Analysis
Now, let's dive into two more powerful panels: Sources and Performance.
V. Sources Panel: The "Operating Room" for JavaScript
In a nutshell: The ultimate debugging center for JavaScript, where you can set breakpoints, step through code, inspect variables, and replace online files.
The "Sources" panel consists of three main parts:
- File Navigator (left): Displays all resources loaded by the page. You can find any JS or CSS file here.
- Code Editor (center): Displays the content of the file you selected.
- Debugger Pane (right): Contains all debugging tools, such as breakpoints, call stack, scope variables, etc.
Core Feature 1: Breakpoints and Code Execution Control
When you set a breakpoint in the code (by clicking on the line number) or trigger an event breakpoint, the code execution will pause there, and a control bar will appear at the top of the page, as shown below:
Simultaneously, control buttons will appear on the right side of the Sources panel as shown below:
This control bar is your remote control for directing code execution. Let's break down the meaning and usage scenarios of each button:
Icon | Name (Official) | Shortcut | Meaning and Usage Scenarios |
---|---|---|---|
▶ | Resume script execution (Resume) | F8 | Meaning: Allows the program to continue executing until it encounters the next breakpoint or the program ends. Scenario: You have finished reviewing the information at the current breakpoint and want the program to continue running. |
↪ | Step over next function call (Step over) | F10 | Meaning: Executes the code on the current line. If the current line is a function call, it will execute the entire function and then stop at the next line. It will not enter the function itself. Scenario: This is the most commonly used single-step debugging operation. You are certain that there are no issues with the function on the current line and only want to see the result after it executes, without getting into the details inside the function. |
⇩ | Step into next function call (Step into) | F11 | Meaning: If the current line is a function call, this operation will enter the function, stopping at the first line of the function body. Scenario: You suspect there is a problem with the function on the current line, or you want to understand its specific implementation, so you need to go inside the function to investigate. |
⇧ | Step out of current function (Step out) | Shift+F11 | Meaning: Executes the remaining part of the current function and then stops at the next line of the code that called this function. Scenario: You entered a function through "Step into," looked at a few lines, and realized there were no issues. You don't want to go through it line by line anymore and want to quickly return to the place where it was called. |
↷ | Step | F9 | Meaning: Similar to "Step over," but more granular. When dealing with asynchronous operations like async/await , "Step" will enter the internal of the asynchronous code, while "Step over" usually skips it. For synchronous code, the two behave similarly.Scenario: Used when debugging the underlying details of an async function. |
Core Feature 2: Local Overrides
This is the "nuclear weapon" of the "Sources" panel. It allows you to replace the JS or CSS being loaded by the online website with your locally modified files.
- In the "Overrides" sub-tab of the "Sources" panel, select a local folder and authorize it.
- In the "Network" panel, right-click the file you want to modify and select "Override content."
- DevTools will open a local copy of the file in the "Sources" panel.
- Modify and save. After refreshing the page, the browser will load your local version. This is extremely efficient for debugging bugs in the production environment.
VI. Performance Panel: The Application's "Electrocardiogram"
In a nutshell: Find performance bottlenecks that cause page lag and frame drops through recording and analysis.
This panel looks complex, but the core idea is simple: record page activity for a period of time and then analyze the report.
How to Use:
- Open the "Performance" panel.
- Click the Record button (⚫) or press
Ctrl+E
/Cmd+E
to start recording. - Perform the actions you want to analyze on the page (e.g., scrolling the page, clicking a button with a complex animation).
- Click the record button again to stop recording.
How to Analyze the Report:
After recording, you'll see a detailed report. Focus on the following sections:
Regarding the flame chart, a detailed analysis is at the bottom of the text.
- Overview: The timeline chart at the top, showing macro metrics such as CPU usage and FPS (frames per second). If you see red bars, it indicates long-running tasks, which are likely the root cause of the lag.
- Main Thread Flame Chart: This is the most important area for analysis.
- It is a Flame Chart, where the X-axis represents time and the Y-axis represents the call stack (the function above is called by the function below).
- Look for wide, yellow blocks: Yellow represents Scripting. A wide yellow block means a JS function executed for a long time, which is the target for optimization.
- Look for wide, purple blocks: Purple represents Rendering & Painting. An overly wide purple block may indicate "forced synchronous layout" or "layout thrashing," which are common performance killers.
- Summary: When you select a task in the flame chart, the summary tab displays the time spent on various activities (such as scripting, rendering, painting) in the task, in the form of a pie chart and a list, helping you quickly locate the most time-consuming parts.
Common Scenarios:
- "Why does the page scroll choppy?" (Record the scrolling process and check the flame chart for long tasks that block the main thread.)
- "Why does the page 'freeze' for a moment after clicking this button?" (Record the click operation and find the JS function that takes too long to execute.)
Appendix: Flame Chart Analysis
It looks very complex, like a jumble of colorful blocks, but don't worry. Once you understand its reading rules, it becomes a powerful tool that clearly tells the story of "how your webpage slows down."
Let's break it down completely, so you can go from "completely clueless" to "able to find problems in it."
I. What is this chart? -- The webpage's "construction recording"
First, imagine it as a high-precision, frame-by-frame recording of the browser's entire "construction process" from opening your webpage to loading it completely. Every step of this process -- downloading files, running code, drawing pixels -- is recorded.
Our goal is to find the workers who are slacking off or unreasonably designed construction steps from this recording, which are the performance bottlenecks.
II. Interpreting the Chart: Top to Bottom, Left to Right
We will interpret this chart by dividing it into three main areas: Top Overview, Middle Main Thread Flame Chart, and Left Insights.
1. Top Overview: Macro Timeline
This part is a miniature of the entire recording process.
- CPU Chart: The undulating yellow, purple, and green chart shows the CPU's busy level. Peaks mean the CPU is working hard.
- Network Track: Shows the timeline of network requests. Each horizontal bar represents a file being downloaded. The longer the bar, the longer the download time.
- Time Scale:
455 ms
,955 ms
... This is the time calculated from the start of page loading. - Key Metric Markers:
FCP
(First Contentful Paint): The time point when the browser first draws something "meaningful" (such as text or images) on the screen.LCP
(Largest Contentful Paint): The time point when the largest image or text block in the viewport is rendered. This is a core metric for measuring user-perceived loading speed. In your screenshot, LCP is as high as 6.63 seconds, which is a signal that needs to be optimized urgently (the ideal value should be within 2.5 seconds).DCL
(DOMContentLoaded): The time point when the HTML document is completely loaded and parsed, excluding style sheets, images, etc.L
(Load): The time point when all page resources (including images, CSS, etc.) are loaded completely.
Summary: Just from looking at the top, we know that this page loads for more than 8 seconds, and users have to wait 6.63 seconds to see the main content, which is a bad experience.
2. Middle Main Thread Flame Chart: The Core of Performance Issues
This is the most important part, and also the most complex part.
Reading Rules:
- X-axis (left to right): Represents Time.
- Y-axis (top to bottom): Represents Call Stack. This is a core concept: The task above is called by the task directly below it.
Color Code:
- Yellow (Scripting): Executing JavaScript code. This is the color that needs the most attention.
- Purple (Rendering & Layout): Calculating styles and layout. The browser is calculating where each element should be and what it should look like.
- Blue (Parsing HTML): Parsing HTML.
- Green (Painting): Painting. The process of the browser actually drawing the calculated elements on the screen.
Key Focus: Long Task
See those task blocks with a small red triangle in the upper right corner?
This represents a "Long Task", which is any task that lasts more than 50ms. The browser's main thread is single-threaded, and when it is executing a long task, it cannot respond to any user operations (such as clicks, scrolling) or render the page, so the page will freeze.
In the screenshot, there are a lot of yellow long tasks, which is the direct cause of the page's poor performance!
Interpretation
- Start Phase (left):
- The browser starts parsing HTML (blue blocks).
- Immediately after, it encounters a lot of JavaScript and starts evaluating scripts, compiling scripts (yellow blocks) for a long time.
- Middle Phase:
- You can see a very wide yellow block, representing a JS task that lasted for a long time.
- Let's zoom in to see the call stack of this task: At the bottom is an anonymous task, which calls
c
,c
calls(anonymous)
, then callsTl.tick
, then callsvu.run
... This long string of stacking is the path of function calls.
* This shows that one or more JS functions executed for too long, completely blocking the main thread.
- Summary: The entire page loading process is repeatedly interrupted and blocked by long-running JavaScript execution. The browser wants to render the page, but is always pulled by JS to do other things, resulting in a very high LCP metric.
3. Left Insights & Bottom Summary
Left Insights
This is a great new feature, which is equivalent to Chrome's AI performance diagnostic doctor. It automatically analyzes the flame chart and tells you what the problem is in easier-to-understand language.
In the screenshot, it points out several problems:
- Render-blocking request: JS or CSS files are blocking the rendering of the page at critical moments.
- Font display: The loading strategy of the webpage font can be optimized to display text faster.
- Use efficient cache lifecycle: Some resources are not cached well, causing them to be downloaded again every time they are accessed.
You should prioritize viewing the suggestions given by Insights, as they usually hit the nail on the head.
Bottom Summary Pane:
When you select any task block in the flame chart, the bottom will display detailed information about the task.
- Summary: Use a pie chart to show the time spent on various activities (scripting, rendering, etc.) in the task.
- Bottom-Up: Tells you which underlying functions take the longest time. This is very useful, it can directly locate the specific most time-consuming functions.
- Call Tree: Display the time-consuming according to the call relationship.
III: Diagnosis
This webpage suffers from severe "JavaScript blockage."
- Core Cause: The main thread is completely occupied by multiple long-running JavaScript tasks (those wide yellow blocks with red triangles).
- Direct Symptoms: Leads to LCP as high as 6.63 seconds, users need to wait a long time to see the main content of the page, and the page may be completely unresponsive to user operations (freezing) during loading.
- Complications: The Insights panel also suggests other problems that can be optimized, such as rendering blocking, fonts, and caching.
Next Action Recommendations:
Focus on Troubleshooting Long Tasks:
- Click on those widest yellow task blocks.
- Switch to the "Bottom-Up" tab at the bottom.
- View the functions with the longest "Total Time" in the list. This is the code you need to optimize!
Optimization Strategies:
- Code Splitting: Is an overly large JS file being loaded? Consider splitting the non-first-screen-required JS code out and loading it on demand.
- Task Decomposition: For that long task that must be executed, can it be broken down into multiple small tasks of no more than 50ms? You can use techniques such as
setTimeout
orrequestIdleCallback
to hand over execution to the browser, giving it a chance to render the page and respond to users. - Algorithm Optimization: Go inside the most time-consuming function, analyze its logic, and see if there are any algorithms that can be optimized, such as reducing the number of loops, avoiding unnecessary DOM operations, etc.