The author | Kayce Basques

Source | Tools for Web Developers

Link | Optimize Website Speed With Chrome DevTools

The target

This tutorial teaches you how to use Chrome DevTools to find ways to make websites load faster.

Read on or watch the video version of this tutorial:

The premise condition

  • You should have basic Web Development experience, similar to the Introduction to Web Development Class.

  • You don’t need to know anything about load performance. You’ll learn about it in this tutorial!

introduce

The next cat is Tony, and he’s very famous in cat circles. He set up a website so fans could learn about his favorite foods. His fans love the site, but Tony keeps complaining that it loads slowly. Tony is now turning to you to help him speed up the loading of his website.

Audit your website

Whenever you want to improve the loading performance of your site, you should start with an audit. Auditing has two important functions:

  • It creates a benchmark for you to measure subsequent improvements.
  • It gives you workable hints as to which changes will have the most impact.

Set up the

First, we need to set up the site so that it can be changed later:

  1. Go to thechrome://versionView the version of Chrome you are using. This tutorial is based on Chrome 68. If you are using an earlier version or higher, some features may look different or not be available. However, you should still be able to complete this tutorial, just keep in mind that your UI may look different from the screenshot.
  2. Open the source code for the site. This TAB is called the Editor TAB.

  1. Click Remix This. The name of the project is changed from Tony to some randomly generated names. You now have your own copy of editable code. You will modify this code later.

  2. Click Show Live. This DEOM will open in a new TAB. This TAB is the Demo TAB. This url may take a while to load.

  1. Press theCommand + Option + J(Mac)orControl + Shift + J(Windows, Linux, Chrome). Chrome DevTools opens with Demo.

For the rest of the screenshots in this tutorial, DevTools will display as a separate window. You can open the Command menu by pressing Command + Shift + P(Mac) or Control + Shift + P(Windows, Linux, Chrome OS), type Undock, Then select Undock into Separate Window to do this.

To establish the benchmark

The benchmark is how the site performed before any performance improvements were made.

  1. Click the Audits TAB. It may be hidden behind the “More Panels” button. There is a Lighthouse on this panel.

  1. Match your audit configuration Settings to those shown above. Here’s a description of the different options:
  • **Device. ** Setting to Mobile changes the user agent string and simulates the Mobile viewport. Set to **Desktop ** to disable Mobile features.
  • **Audits. ** Disabling a category prevents the Audits panel from running these Audits and removing those audit items from the report. Disabling categories speeds up the audit process slightly.
  • Set to **Simulated Fast 3G, 4X CPU Slowdown ** which simulates typical conditions for browsing a page on a mobile device. It is called “emulation” because the Audits panels don’t actually throttle during auditing. Instead, it simply extrapolates the time required for the page to load under moving conditions. On the other hand, the Applied Fast 3G, 4X CPU Slowdown setting actually limits your CPU and network, requiring a longer audit process to be balanced.
  • Clear Storage. Enabling this check box clears all Storage associated with the page before each audit. Keep this setting if you want to audit how first-time visitors experience your site. Disable this setting when you need to repeat the experience.
  1. Click Run Audits. After 10 to 30 seconds, the Audits panel will show you a performance report for that site.

Handle reported errors

If you encounter errors in the Audits panel reports, try running the Demo TAB from Incognito Window without opening the other tabs. This ensures that you run Chrome clean. Chrome extensions in particular often interfere with the audit process.

Understand your report

The number at the top of the report is the site’s overall effectiveness score. Later, when you make changes to the code, you will see this number increase. A higher score indicates better performance.

Time To Interactive

Learn More

Metrics

The Opportunities section provides specific tips on how to improve the loading performance of this particular page.

Click Learn More to see documentation on why opportunity is so important and specific suggestions on how to address it.

Diagnostics

Passed Audits

Step 2: the actual combat

The Opportunities section of the audit report gives you tips on how to improve page performance. In this section, we’ll take these suggestions and modify the code, reviewing the site after each change to measure how it affects site speed.

Enabling text compression

Enabling text compression is one of the main ways to improve page performance, the report says.

Text compression refers to reducing or compressing the size of a text file before sending it over the network. This is similar to the way you compress a folder to reduce its size when sending it via email.

Before enabling compression, you can manually check whether the text resource is compressed by using the following two methods.

  1. Click the Network TAB.

  1. Click Use Large Request Rows. The row height in the network request table increases.

  1. If you do not see the Size column in the network request table, right-click the table header and select Size.

Each Size cell displays two values. The value above is the size of the downloaded resource. Below is the size of the uncompressed resource. If the two values are the same, the resource is not compressed when it is sent over the network. For example, in the figure above, the bundle.js values are 1.4MB above and below.

You can also check compression by examining the HTTP header of the resource:

  1. Click the bundle. Js.
  2. Click the Header TAB.

  1. inResponse HeaderIn the searchcontent-encodingHead. You shouldn’t see that, which meansbundle.jsIt’s not compressed. After the resource is compressed, this header is usually set togzip , deflate 或 br. Please refer to these values for a descriptionhere.

That’s about it. Let’s make some changes! Enable text compression by adding a few lines of code:

  1. In the editor TAB, click server.js.

  1. Add the following code toserver.js. Ensure that theapp.use(compression())On theapp.use(express.static('build'))Before.
. const fs =require('fs');
const compression = require('compression');
app.use(compression());
app.use(express.static('build')); .Copy the code

Note: Normally, you would have to install a compression package through something like NPM I-S Compression, but here we did that in advance.

Wait for Glitch to deploy the new version of the site. You’ll see nice animations next to Logs and Show, indicating that the site is being rebuilt and redeployed. When you see Show Live again, the changes are deployed.

  1. Return to the Demo TAB and reload the page. Now,SizeColumns should display 2 different values for text resources (such as bundle.js). In the figure below, the value above bundle.js261 KBIs the size of the file sent over the network, and the following values1.4 MBIs the size of the uncompressed file.

  1. bundle.js 的 Response HeaderSection should now contain onecontent-encodingThe header.

  1. Click the Audits TAB.
  2. Click Perform an Audit.
  3. Keep the same Settings as before.
  4. Click Run Audit.

Real world text compression

In fact, most servers do have simple programs that enable compression! Simply search for any server that is configured to compress text.

Resize the image

In the new report, the prompt to properly resize images is also an improvement.

Resizing images can help speed up load times by reducing the image file size. If your users are viewing images on a mobile device screen 500 pixels wide, it really doesn’t make sense to send images 1500 pixels wide. Ideally, you can only send images up to 500 pixels wide.

  1. In the report, click on propersize Images to see which image should be resized. It looks like all 4 images are more than needed.

  1. Return to the Editor TAB and opensrc/model.js.
  2. willconst dir = 'big'Replace withconst dir ='small'. This directory contains copies of the same image that have been resized.
  3. Audit the page again to see how this change affects load performance.

5.3 M
0.18 M

Resize images in the real world

For small applications, such a one-time resizing might be sufficient. But for large applications, this is obviously not extensible. Here are some strategies for managing images in large applications:

  • Resizing images during the build process.
  • Create multiple dimensions for each image during the build process, and then use srCset in your code. At runtime, the browser selects the size that best fits the device on which it is running. See relative-sized imaged.
  • Use an image CDN that lets you dynamically resize an image when requested.
  • At least optimize each image. This can often save a lot of traffic. Optimization is when an image is run through a special program that reduces the size of the image file. For more tips, see Essential Image Optimization.

Remove render blocking resources

In the latest report, hints can be made to try to eliminate rendering blocking resources.

The resources that block rendering are external JavaScript or CSS files that the browser must download, parse, and execute before displaying the page. The goal is to run only the core CSS and JavaScript code needed to display the page correctly.

The first task is to find code that doesn’t need to be executed when the page loads.

  1. Click on theEliminate render-blocking resourceTo view blocked resources:lodash.js 和 jquery.js 。

  1. According to theCommand + Shift + P(Mac) 或 Control + Shift + P(Windows, Linux, Chrome OS)Open the Commands menu, type Coverage, and selectShow Coverage.

  1. Click on theReload. The Coverage TAB Outlines how the page is executing when it loadsbundle.js , jquery.js 和 lodash.jsHow much code in. Figure 32 shows that the unused code in the jQuery and Lodash files is about 76% and 30%, respectively.

  1. Click on the jquery.js line. DevTools opens the file in the Source panel. If a line of code has a green bar next to it, that line of code has been executed. The red bar indicates that it is not executed and is definitely not needed at page load time.

  1. Scroll through the jQuery code. Some of the lines that are “executed” are really just comments. Running this code through the annotated minifier is another way to reduce the size of this file.

In short, when you work with your own code, the Coverage TAB helps you analyze it line by line and deliver only as much code as the page needs to load.

Do you need jquery.js and lodash.js files to load the page? The Request Blocking TAB shows what happens when a resource is unavailable.

  1. Click the Network TAB.
  2. According to theCommand + Shift + P(Mac) 或 Control + Shift + P(Windows, Linux, Chrome OS)Open the Command menu again.
  3. Start typingblockingAnd then selectShow Request Blocking.

  • Click on theAdd Pattern, type/libs/*And then pressEnterConfirmation.

  • Reload the page. JQuery and Lodash requests are red to indicate that they have been blocked. The page is still loaded and interactive, so it looks like none of these resources are needed!

  1. Click on theRemove all patternsTo remove the/libs/*Blocking mode

In general, the Request Blocking TAB can be used to simulate the behavior of a page when any given resource is unavailable.

Now, remove references to these files from the code, and audit the page again:

  1. Return to the Editor TAB and opentemplate.html 。
  2. delete<script src ="/libs/lodash.js"> 和 <script src ="/libs/jquery.js"></script> 。
  3. Wait for the site to rebuild and redeploy.
  4. Audit the pages again in the Audits panel. Your overall score should improve again.

Optimize key render paths in real projects

The key render path is the code required to load the page. Typically, you can speed up page loading by delivering key code only during page loading and then lazily loading everything else.

  • You are unlikely to find scripts that can be removed completely, but you will often find that many scripts are not required during page loading and can be requested asynchronously. See Using asynchrony or delay.
  • If you are using a framework, check to see if it has production mode. This pattern can use features like Tree Shaking to remove unnecessary code that blocks critical rendering.

Reduce main thread work

The latest report shows some potential optimizations in the Opportunities section, but if you look at them in the Diagnostics section, it appears that the biggest bottleneck is excessive mainline activity.

The main thread is where the browser does most of the work required to display the page, such as parsing and executing HTML, CSS, and JavaScript.

The goal is to use the Performance panel to analyze what the main thread is doing when the page loads, and to find ways to delay or remove unnecessary work.

  1. Click the Performance TAB.
  2. Click Capture Settings.
  3. Set Network to Slow 3G and CPU to 6x Slowdowns. Mobile devices typically have more hardware limitations than laptops or desktops, so these Settings allow you to experience page loading as if you were using a less powerful device.
  4. Click the Reload. DevTools will reload the page and then generate a visualization to show that the page is fully loaded. The visual page will be called Trace.

Trace displays activities chronologically from left to right. The FPS, CPU, and NET chart at the top summarizes frames per second, CPU activity, and network activity. The yellow bars seen in the figure below indicate that the CPU is fully occupied with scripting activity. This shows that you can speed up page loading by reducing JavaScript effort.

  1. Click the User Timing section to expand it. Based on the fact that there seems to be a lot of User Timing from React, it looks like Tony’s application is using React development mode. Switching to React production mode may lead to some performance optimizations.

  1. Click User Timing again to collapse the section.

  2. 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 occur. For example, in the figure below, the Evaluate Script event causes the function to execute (anonymous), which causes the execution of.. /rbd/pnpm-volume/… , causing __webpack__require__ to be executed, and so on.

Main
mineBitcoin

Note: Although the calls made by the framework are usually out of your control, sometimes you can structure your application in a way that prevents the framework from running efficiently. Reorganizing your application to use the framework effectively is one way to reduce the work of the main thread. However, this requires an in-depth understanding of how the framework works and what changes you can make in your own code to use the framework more effectively.

  1. Expand the bottom-up section. This TAB breaks down which activities take up the most time. If you don’t see anything in the ** bottom-up ** section, click the TAB in the Main section. ** bottom-up ** displays only information about the currently selected activity or activity group. For example, if you click on one of the mineBitcoin activities, ** bottom-up ** will display only information for that activity.

The Self Time column shows you how much Time you spend directly on each activity. For example, the figure above shows that about 57% of the main thread time is spent in the mineBitcoin function.

It’s time to see if using production mode and reducing JavaScript activity will speed up page loading. Start with the production model:

  1. In the Editor TAB, openwebpack.config.js 。
  2. will"mode": "development"Change to"mode": "production" 。
  3. Wait for a new build to deploy.
  4. Review the page again.

Reduce JavaScript activity by removing the call to mineBitcoin:

  1. In the Editor TAB, opensrc/App.jsx 。
  2. Comment out pairs in the constructorthis.mineBitcoin(1500)The call.
  3. Wait for a new build to deploy.
  4. Audit the page again.

Note: This section provides a fairly brief introduction to the Performance panel. See the Performance Analysis Reference for more information on how to use it to analyze page performance.

Reduce mainline work in real projects ** In general, the Performance panel is the most common way to learn about the activities your site performs when it loads and find ways to remove unnecessary activities.

If you want to use a more console.log() approach, you can use the User Timing API to arbitrarily mark certain phases of the application life cycle to keep track of how long each phase takes.

Special thanks from Tony

Tony’s fans love the speed of this site and Tony is very grateful for your help. Click Receive Gifts below to receive a special gift from Tony.

conclusion

  • Whenever you set out to optimize the load performance of your site, always start with an audit. Audits will establish benchmarks and provide you with hints for improvements.
  • Make the changes step by step and audit the page after each change to see how the isolated change affects performance.