Optimize Website Speed With Chrome DevTools
source link: https://www.tuicool.com/articles/hit/me67vaV
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Goal of tutorial
This tutorial teaches you how to use Chrome DevTools to find ways to make your websites load faster.
Prerequisites
- You should have basic web development experience, similar to what's taught in this Introduction to Web Development class .
- You don't need to know anything about load performance. You'll learn about it in this tutorial!
Introduction
This is Tony. Tony is very famous in cat society. He has built a website so that his fans can learn what his favorite foods are. His fans love the site, but Tony keeps hearing complaints that the site loads slowly. Tony has asked you to help him speed the site up.
Figure 1 . Tony the catStep 1: Audit the site
Whenever you set out to improve a site's load performance, always start with an audit . The audit has 2 important functions:
- It creates a baseline for you to measure subsequent changes against.
- It gives you actionable tips on what changes will have the most impact.
Set up
But first, you need to set up the site so that you can make changes to it later:
- Go to
chrome://version
to check what version of Chrome you're using. This tutorial was made with Chrome 68. If you're using an earlier or later version, some features may look different or not be available. You should be able to complete the tutorial still, just keep in mind that your UI may look different than the screenshots. -
Open the source code for the site . This tab will be referred to as the editor tab .
Figure 2 . The editor tab -
Click tony . A menu appears.
Figure 3 . The menu that appears after clicking tony -
Click Remix This . The name of the project changes from tony to some randomly-generated name. You now have your own editable copy of the code. Later on, you'll make changes to this code.
-
Click Show Live . The demo opens in a new tab. This tab will be referred to as the demo tab . It may take a while for the site to load.
Figure 4 . The demo tab -
Press Command + Option + J (Mac) Control + Shift + J (Windows, Linux, Chrome OS). Chrome DevTools opens up alongside the demo.
Figure 5 . DevTools and the demo
For the rest of the screenshots in this tutorial, DevTools will be shown as a separate window. You can do this by pressing Command + Shift + P (Mac) or Control + Shift + P (Windows, Linux, Chrome OS) to open the Command Menu, typing Undock
, and then selecting Undock into separate window .
Establish a baseline
The baseline is a record of how the site performed before you made any performance improvements.
-
Click the Audits tab. It may be hidden behind the More Panels button. There's a Lighthouse on this panel because the project that powers the Audits panel is calledLighthouse.
Figure 7 . The Audits panel -
Match your audit configuration settings to those in Figure 8 .
-
Click Run Audits . After 10 to 30 seconds, the Audits panel shows you a report of the site's performance.
Figure 8 . The Audits panel's report of the site's performance
Handling report errors
If you ever get an error in your Audits panel report, try running the demo tab from anincognito window with no other tabs open.
Figure 9 . A report that erroredUnderstand your report
The number at the top of your report is the overall performance score for the site. Later, as you make changes to the code, you should see this number rise. A higher score means better performance.
Figure 10 . The overall performance scoreThe Metrics section provides quantitative measurements of the site's performance. Each metric provides insight into a different aspect of the performance. For example, First Contentful Paint tells you when content is first painted to the screen, which is an important milestone in the user's perception of the page load, whereas First CPU Idle marks when the main thread is quiet enough to handle user input, which is essentially a proxy for when the user can first interact with the page.
Figure 11 . The Metrics sectionHover over a metric to see a description of it, and click Learn More to read documentation about it.
Figure 12 . Hovering over the First Meaningful Paint metricBelow Metrics is a collection of screenshots that show you how the page looked as it loaded.
Figure 13 . Screenshots of how the page looked while loadingThe Opportunities section provides specific tips on how to improve this particular page's load performance.
Figure 14 . The Opportunities sectionClick an opportunity to learn more about it.
Figure 15 . More information about the text compression opportunityClick Learn More to see documentation about why an opportunity is important, and specific recommendations on how to fix it.
Figure 16 . Documentation for the text compression opportunityThe Diagnostics section provides more information about factors that contribute to the page's load time.
Figure 17 . The Diagnostics sectionThe Passed Audits section shows you what the site is doing correctly. Click to expand the section.
Figure 18 . The Passed Audits sectionStep 2: Experiment
The Opportunities section of your audit report gives you tips on how to improve the page's performance. In this section, you implement the recommended changes to the codebase, auditing the site after each change to measure how it affects site speed.
Enable text compression
Your report says that enabling text compression is one of the top opportunities for improving the page's performance.
Text compression is when you reduce, or compress, the size of a text file before sending it over the network. Kind of like how you might zip a folder before emailing it to reduce its size.
Before you enable compression, here are a couple of ways you can manually check whether text resources are compressed.
-
Click the Network tab.
Figure 19 . The Network panel -
Click Use Large Request Rows . The height of the rows in the table of network requests increases.
Figure 20 . Large rows in the network requests table -
If you don't see the Size column in the table of network requests, click the table header and then select Size .
Each Size cell shows two values. The top value is the size of the downloaded resource. The bottom value is the size of the uncompressed resource. If the two values are the same, then the resource is not being compressed when it's sent over the network. For example, in Figure 20 the top and bottom values for bundle.js
are both 1.4 MB
.
You can also check for compression by inspecting a resource's HTTP headers:
- Click bundle.js .
-
Click the Headers tab.
Figure 21 . The Headers tab -
Search the Response Headers section for a
content-encoding
header. You shouldn't see one, meaning thatbundle.js
was not compressed. When a resource is compressed, this header is usually set togzip
,deflate
, orbr
. See Directives for an explanation of these values.
Enough with the explanations. Time to make some changes! Enable text compression by adding a couple of lines of code:
-
In the editor tab, click server.js .
Figure 22 . Editingserver.js
-
Add the following code to server.js . Make sure to put
app.use(compression())
beforeapp.use(express.static('build'))
.... const fs = require('fs'); <strong>const compression = require('compression');</strong> <strong>app.use(compression());</strong> app.use(express.static('build')); ...
-
Wait for Glitch to deploy the new build of the site. The fancy animation that you see next to Logs and Show means that the site is getting rebuilt and redeployed. The change is ready when you see Show Live again.
Figure 23 . The animation that indicates that the site is getting built
Use the workflows that you learned earlier to manually check that the compression is working:
-
Go back to the demo tab and reload the page. The Size column should now show 2 different values for text resources like
Figure 24 . The Size column now shows 2 different values for text resourcesbundle.js
. In Figure 24 the top value of261 KB
forbundle.js
is the size of the file that was sent over the network, and the bottom value of1.4 MB
is the uncompressed file size. -
The Response Headers section for
Figure 25 . The Response Headers section now contains abundle.js
should now include acontent-encoding: gzip
header.content-encoding
header
Audit the page again to measure what kind of impact text compression has on the page's load performance:
- Click the Audits tab.
- Click Perform an audit .
- Leave the settings the same as before.
-
Click Run audit .
Figure 26 . An Audits report after enabling text compression
Woohoo! That looks like progress. Your overall performance score should have increased, meaning that the site is getting faster.
Text compression in the real world
Most servers really do have simple fixes like this for enabling compression! Just do a search on how to configure whatever server you use to compress text.
Resize images
Your new report says that properly sizing images is another big opportunity.
Resizing images helps speed up load time by reducing the file size of images. If your user is viewing your images on a mobile device screen that's 500-pixels-wide, there's really no point in sending a 1500-pixel-wide image. Ideally, you'd send a 500-pixel-wided image, at most.
-
In your report, click Properly size images to see what images should be resized. It looks like all 4 images are bigger than necessary.
Figure 27 . Details about the Properly size images opportunity -
Back in the editor tab, open
src/model.js
. - Replace
const dir = 'big'
withconst dir = 'small'
. This directory contains copies of the same images which have been resized. -
Audit the page again to see how this change affects load performance.
Figure 28 . An Audits report after resizing images
Looks like the change only has a minor affect on the overall performance score. However, one thing that the score doesn't show clearly is how much network data you're saving your users. The total size of the old photos was around 5.3 megabytes, whereas now it's only about 0.18 megabytes.
Resizing images in the real world
For a small app, doing a one-off resize like this may be good enough. But for a large app, this obviously isn't scalable. Here are some strategies for managing images in large apps:
- Resize images during your build process.
-
Create multiple sizes of each image during the build process and then use
srcset
in your code. At runtime, the browser takes care of choosing what size is best for the device it's running on. See Relative-sized images . -
Use an image CDN that lets you dynamically resize an image when you request it.
- At the very least, optimize each image. This can often create huge savings. Optimization is when you run an image through a special program that reduces the size of the image file. See Essential Image Optimization for more tips.
Eliminate render-blocking resources
Your latest report says that eliminating render-blocking resources is now the biggest opportunity.
A render-blocking resource is an external JavaScript or CSS file that the browser must download, parse, and execute before it can show the page. The goal is to only run the core CSS and JavaScript code that is required to display the page properly.
The first task, then, is to find code that doesn't need to be executed on page load.
-
Click Eliminate render-blocking resources to see the resources that are blocking:
Figure 29 . More information about the Reduce render-blocking resources opportunitylodash.js
andjquery.js
. -
Press Command + Shift + P (Mac) or Control + Shift + P (Windows, Linux, Chrome OS) to open the Command Menu, start typing
Figure 30 . Opening the Command Menu from the Coverage tab Figure 31 . The Coverage tabCoverage
, and then select Show Coverage . -
Click Reload . The Coverage tab provides an overview of how much of the code in
Figure 32 . The Coverage reportbundle.js
,jquery.js
, andlodash.js
is being executed while the page loads. Figure 32 says that about 76% and 30% of the jQuery and Lodash files aren't used, respectively. -
Click the jquery.js row. DevTools opens the file in the Sources panel. A line of code was executed if it has a green bar next to it. A red bar means it was not executed, and is definitely not needed on page load.
Figure 33 . Viewing the jQuery file in the Sources panel -
Scroll through the jQuery code a bit. Some of the lines that get "executed" are actually just comments. Running this code through a minifier that strips comments is another way to reduce the size of this file.
In short, when you're working with your own code, the Coverage tab can help you analyze your code, line-by-line, and only ship the code that's needed for page load.
Are the jquery.js
and lodash.js
files even needed to load the page? The Request Blocking tab can show you what happens when resources aren't available.
- Click the Network tab.
- Press Command + Shift + P (Mac) or Control + Shift + P (Windows, Linux, Chrome OS) to open the Command Menu again.
-
Start typing
Figure 34 . The Request Blocking tabblocking
and then select Show Request Blocking . -
Click Add Pattern , type
Figure 35 . Adding a pattern to block any request to the/libs/*
, and then press Enter to confirm.libs
directory -
Reload the page. The jQuery and Lodash requests are red, meaning that they were blocked. The page still loads and is interactive, so it looks like these resources aren't needed whatsoever!
Figure 36 . The Network panel shows that the requests have been blocked -
Click Remove all patterns to delete the
/libs/*
blocking pattern.
In general, the Request Blocking tab is useful for simulating how your page behaves when any given resource isn't available.
Now, remove the references to these files from the code and audit the page again:
- Back in the editor tab, open
template.html
. - Delete
<script src="/libs/lodash.js">
and<script src="/libs/jquery.js"></script>
. - Wait for the site to re-build and re-deploy.
-
Audit the page again from the Audits panel. Your overall score should have improved again.
Figure 37 . An Audits report after removing the render-blocking resources
Optimizing the Critical Rendering Path in the real-world
The Critical Rendering Path refers to the code that you need to load a page. In general, you can speed up page load by only shipping critical code during the page load, and then lazy-loading everything else.
- It's unlikely that you'll find scripts that you can remove outright, but you will often find that many scripts don't need to be requested during the page load, and can instead be requested asynchronously. SeeUsing async or defer.
- If you're using a framework, check if it has a production mode. This mode may use a feature such as tree shaking in order to eliminate unnecessary code that is blocking the critical render.
Do less main thread work
Your latest report shows some minor potential savings in the Opportunities section, but if you look down in the Diagnostics section, it looks like the biggest bottleneck is too much main thread activity.
The main thread is where the browser does most of the work needed to display a page, such as parsing and executing HTML, CSS, and JavaScript.
The goal is to use the Performance panel to analyze what work the main thread is doing while the page loads, and find ways to defer or remove unnecessary work.
- Click the Performance tab.
- Click Capture Settings .
- Set Network to Slow 3G and CPU to 6x slowdown . Mobile devices typically have more hardware constraints than laptops or desktops, so these settings let you experience the page load as if you were using a less powerful device.
-
Click Reload . DevTools reloads the page and then produces a visualization of all the it had to do in order to load the page. This visualization will be referred to as the trace .
Figure 38 . The Performance panel's trace of the page load
The trace shows activity chronologically, from left to right. The FPS, CPU, and NET charts at the top give you an overview of frames per second, CPU activity, and network activity. The wall of yellow that you see in Figure 39 means that the CPU was completely busy with scripting activity. This is a clue that you may be able to speed up page load by doing less JavaScript work.
Figure 39 . The Overview section of the traceInvestigate the trace to find ways to do less JavaScript work:
-
Click the User Timing section to expand it. Based on the fact that there seems to be a bunch of User Timing measures from React, it seems like Tony's app is using the development mode of React. Switching to the production mode of React will probably yield some easy performance wins.
Figure 40 . The User Timing section -
Click User Timing again to collapse that section.
-
Browse the Main section. This section shows a chronological log of main thread activity, from left to right. The y-axis (top to bottom) shows why events occurred. For example, in Figure 41 , the
Figure 41 . The Main sectionEvaluate Script
event caused the(anonymous)
function to execute, which caused../rbd/pnpm-volume/...
to execute, which caused__webpack__require__
to execute, and so on. -
Scroll down to the bottom of the Main section. When you use a framework, most of the upper activity is caused by the framework, which is usually out of your control. The activity caused by your app is usually at the bottom. In this app, it seems like a function called
Figure 42 . Hovering over theApp
is causing a lot of calls to amineBitcoin
function. It sounds like Tony might be using the devices of his fans to mine cryptocurrency...mineBitcoin
activity -
Expand the Bottom-Up section. This tab breaks down what activities took up the most time. If you don't see anything in the Bottom-Up section, click the label for Main section. The Bottom-Up section only shows information for whatever activity, or group of activity, you have currently selected. For example, if you clicked on one of the
Figure 43 . The Bottom-Up tabmineBitcoin
activities, the Bottom-Up section is only going to show information for that one activity.
The Self Time column shows you how much time was spent directly in each activity. For example, Figure 43 shows that about 57% of main thread time was spent on the mineBitcoin
function.
Time to see whether using production mode and reducing JavaScript activity will speed up the page load. Start with production mode:
- In the editor tab, open
webpack.config.js
. - Change
"mode":"development"
to"mode":"production"
. - Wait for the new build to deploy.
-
Audit the page again.
Figure 44 . An Audits report after configuring webpack to use production mode
Reduce JavaScript activity by removing the call to mineBitcoin
:
- In the editor tab, open
src/App.jsx
. - Comment out the call to
this.mineBitcoin(1500)
in theconstructor
. - Wait for the new build to deploy.
-
Audit the page again.
Figure 45 . An Audits report after removing unnecessary JavaScript work
Looks like that last change caused a massive jump in performance!
Doing less main thread work in the real world
In general, the Performance panel is the most common way to understand what activity your site does as it loads, and find ways to remove unnecessary activity.
If you'd prefer an approach that feels more like console.log()
, the User Timing API lets you arbitrarily mark up certain phases of your app lifecycle, in order to track how long each of those phases takes.
A special thank you from Tony
Tony's fans love how fast the site feels now, and Tony is very thankful for your help. Click Receive Gift below to receive a special gift from Tony.
[This section requires a browser that supports JavaScript and iframes.]
Summary
- Whenever you set out to optimize a site's load performance, always start with an audit. The audit establishes a baseline, and gives you tips on how to improve.
- Make one change at a time, and audit the page after each change in order to see how that isolated change affects performance.
Next steps
- Run audits on your own site! If you need help interpreting your report, or finding ways to improve your load performance, check outfor ways to get help from the DevTools community. Stack Overflow, the mailing list, or Twitter are probably best for these types of questions.
- Please leaveon this tutorial. I really do use the data to make better tutorials for you.
Feedback
[This section requires a browser that supports JavaScript and iframes.]
[This section requires a browser that supports JavaScript and iframes.]
If there's anything else we should know, please send a message through the appropriate channel:
- File bugs on this doc in the Web Fundamentals repository.
- File bug reports on DevTools at Chromium Bugs .
- Discuss features and changes on theMailing List. Please don't use the mailing list for support questions. Use Stack Overflow, instead.
- Get general help on how to use DevTools on Stack Overflow . Please don't file bugs on Stack Overflow. Use Chromium Bugs, instead.
- Tweet us at @ChromeDevTools .
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK