Coding With Fun
Home Docker Django Node.js Articles FAQ

10 quick and effective ways to optimize web performance


May 31, 2021 Article blog


Table of contents


The article comes from the public number: full brain hole, author: crazy tech house

Optimizing your site's performance can take a lot of time, and it can take more time to optimize to suit your needs.

In this article, I'll show you 10 ways to quickly optimize web performance for your own site in 5 minutes. T hese shortcuts have little impact on your code base or server configuration. They're simple and easy to implement, don't need to learn more about how they work, and can have a significant impact on your performance.

1. Use text compression

Text compression minimizes the number of bytes transferred over the network. T here are several compression algorithms. gzip is the most popular, but Brotli is an updated or even better compression algorithm. If you want to check whether the server supports Brotli, you can use the Brotli.pro tool.

If your server doesn't support Brotli, you can install it by following these simple guidelines:

  • Nginx on Linux [4]
  • Apache [5]
  • NodeJs - Express [6]

This is the first optimization you can get for free, and most managed platforms or CDNs provide compression by default.

2. Image compression

Uncompressed images are a potentially huge performance bottleneck. I f the image is not compressed, it consumes a lot of bandwidth. T here are several useful tools for quickly compressing images without losing visible quality. I usually use Imagemin . It supports a variety of image formats, and you can either use the command-line interface or the npm module.

imagemin img/* --out-dir=dist/images

You can use npm module in packages such as webpack gulp or grunt

const imagemin = require('imagemin');
const imageminMozjpeg = require('imagemin-mozjpeg');


(async() => {
  const files = await imagemin(
      ['img/*.jpg'],
      {
        destination: 'dist/img',
        plugins: [
          imageminMozjpeg({quality: 60}),
        ]
      }
  );
  console.log(files);
})();

In general, you can reduce a 4MB file size to 100kB. You can view the demo code in Github.

unit File size, no compression Compress the file size The file size is reduced by a percentage
Bytes 4156855 Bytes 103273 Bytes -97%
MB/kB 4MB 103 kB -97%

3. Picture format

Using modern image formats can really improve performance. W ebP images are smaller than JPEG and PNG, typically 25% to 35% smaller. WebP is widely supported by browsers.

We use imagemin npm package and add a WebP plug-in to it. The following code outputs the WebP version of the image to the dist folder.

const imagemin = require('imagemin');
const imageminWebp = require('imagemin-webp');


(async() => {
  const files = await imagemin(
      ['img/*.jpg'],
      {
        destination: 'dist/img',
        plugins: [
          imageminWebp({quality: 50})
        ]
      }
  );
  console.log(files);
})();

Take another look at the file size:

unit File size, no compression Compress the file size The file size is reduced by a percentage
Bytes 4156855 Bytes 58940 Bytes -98%
MB/kB 4MB 59 kB -98%

The results showed that the file size was reduced by 98% compared to the original image, and that WebP compressed the image more significantly than the compressed JPG file. The WebP version is 43% smaller than the compressed JPEG version.

4. Image lazy loading

Image lazy loading is a technique for loading images later that are temporarily not displayed on the screen. L oading immediately when the parser encounters an image slows down the initial page. W ith lazy loading, you can speed up the page loading process and load images later. T his can be done easily with lazysizes. You can put the following code:

<img src="image.jpg" alt="">

Change to:

<img data-src="image.jpg" class="lazyload" alt="">

lazysizes library handles the rest of the work and can be verified using a browser. O pen your site and find the image label. If the class changes from lazyload to lazyloaded it means it works.

5. Cache your resources: HTTP cache header

Caching is a way to quickly speed up your site. I t reduces page load times for older users. If you have access to the server cache, it's easy to use.

You can cache using the following APIs:

  • Cache-Control [14]
  • ETag [15]
  • Last-Modified [16]

6. Inline Critical CSS: Postponing Non-Critical CSS

CSS is render blocked. T his means that the browser must download and process all CSS files before it can draw pixels. This process can be greatly accelerated by inline critical CSS.

You can follow these steps:

Identify critical CSS

If you don't know what your key CSS is, you can help with Critcal, CriticalCSS, or Penthouse. These libraries are used to extract CSS from HTML files that are visible in a given viewport.

The following is an example of using criticalCSS

var criticalcss = require("criticalcss");


var request = require('request');
var path = require( 'path' );
var criticalcss = require("criticalcss");
var fs = require('fs');
var tmpDir = require('os').tmpdir();


var cssUrl = 'https://web.dev/app.css';
var cssPath = path.join( tmpDir, 'app.css' );
request(cssUrl).pipe(fs.createWriteStream(cssPath)).on('close', function() {
  criticalcss.getRules(cssPath, function(err, output) {
    if (err) {
      throw new Error(err);
    } else {
      criticalcss.findCritical("https://web.dev/", { rules: JSON.parse(output) }, function(err, output) {
        if (err) {
          throw new Error(err);
        } else {
          console.log(output);
          // 将其保存到文件以进行第 2 步
        }
      });
    }
  });
});

Inline critical CSS

Critical CSS is processed immediately when html parsers encounter style tags.




  
  body {...}
  /* ... 其余的关键CSS */

  

Delays are not important to CSS

Non-critical CSS does not require immediate processing. The browser can load the onload event after it, so that the user does not have to wait.




7. JavaScript asynchronous and lazy loading

JavaScript is blocked by HTML parsers. T he browser must wait for JavaScript to perform to complete the resolution of the HTML. But you can tell the browser to wait for JavaScript to execute.

Load JavaScript asynchronously

With the async property, you can tell the browser to load the script asynchronously.


Defer JavaScript

The defer property tells the browser to run the script after the HTML parser has resolved the document, but domContentLoaded is triggered before the event occurs.


Adjust the position of the inline script

The inline script executes immediately and is resolved by the browser. Therefore, you can place them at the end of the HTML, immediately before the body tag.

8. Use resource tips to speed delivery.

Resource Tip . . . . The specification defines four pronams:

  • Preconnect (pre-connected)
  • dns-prefetch (DNS prefetch)
  • prefetch (prefetch)
  • Prerender (pre-rendered)

In addition, for resource tips, we use the preload (21) keyword for link property.

preconnect

The following code tells the browser that you want to establish a connection to another domain. T he browser will prepare for this connection. U sing pre-connected link labels can reduce load times by 100-500 ms. S o when should I use it? T o be blunt: When you know where to take something but don't know how to take it. Things like hash style styles.2f2k1kd.css


 

dns-prefetch

If you want to tell your browser that you are going to establish a connection to a non-critical domain, you can dns-prefetch This saves you about 20-120 milliseconds.


 

prefetch

With pre-retrieval, you can tell your browser to download the entire site referred to in the link tag. Y ou can pre-pick pages or resources. Pre-picking is useful for speeding up your site, but be aware of situations where it is possible to slow down your site.

You may experience problems with low-end devices or slow internet speeds because your browser is always busy pre-picking. You might consider using pre-fetching in conjunction with adaptive loading, or you might combine smart pre-fetching with quicklink and Guess .js.










prerender


When you use pre-rendering, the content is loaded first, and then rendered in the background. When the user navigates to pre-rendered content, the content is displayed immediately.

preload

With the preload feature, the browser is prompted that the referenced resource is important and should be available as soon as possible. M odern browsers are good at prioritizing resources, so you should only use preloading for critical resources. Consider pre-connecting and pre-picking instead, or try using instant.page .


9. Use Google Fonts

Google Fonts is great. T hey provide quality service and are widely used. G oogle Fonts is a great choice if you don't want to host your own fonts. B ut you should pay attention to how to implement them. erts has written a great article about how to use Google Fonts to speed up your site. It is highly recommended to read.

If you just want to know how to use it, you can integrate Google Fonts with the following snippets, but thanks to Harry.








10. Cache your resources with a service worker

Service worker is a script that the browser runs in the background. C aching is one of the most commonly used features and the one you should use most. I don't think it's a question of choice. With service worker caching, users can interact faster with your site and access your site even when users are disconnected.

summary

In this article, I'll show you 10 ways to quickly optimize web performance that can be used on your own website in 5 minutes. You can find the relevant resources in GitHub.

Here's a look at W3Cschool编程狮 introduction to the 10 quick and effective ways to optimize web performance.

Resources

[1]gzip: https://www.youtube.com/watch?v=whGwm0Lky2s&feature=youtu.be&t=14m11s

[2] Brotli: https://opensource.googleblog.com/2015/09/introducing-brotli-new-compression.html

[3] Brotli.pro: https://www.brotli.pro/

[4] Nginx on Linux: https://computingforgeeks.com/how-to-enable-gzip-brotli-compression-for-nginx-on-linux/

[5] Apache: https://bash-prompt.net/guides/apache-brotoli/

[6] NodeJs - Express: https://web.dev/codelab-text-compression-brotli/

[7] Imagemin: https://github.com/imagemin/imagemin

Use under the command line interface: https://github.com/imagemin/imagemin-cli

npm module: https://www.npmjs.com/package/imagemin

[10] View the demo code in Github: https://github.com/marcradziwill/web-performance-quick-wins-tutorial

[11] WebP is widely supported by browsers: https://caniuse.com/#feat=webp

[12] WebP plug-in: https://www.npmjs.com/package/imagemin-webp

[13]lazysizes: https://github.com/aFarkas/lazysizes

[14] Cache-Control: https://developer.mozilla.org/de/docs/Web/HTTP/Headers/Cache-Control#Browser_compatibility

[15] ETag: https://developer.mozilla.org/docs/Web/HTTP/Headers/ETag#Browser_compatibility

[16] Last-Modified: https://developer.mozilla.org/docs/Web/HTTP/Headers/Last-Modified#Browser_compatibility

[17] Critcal: https://github.com/addyosmani/critical

[18] CriticalCSS: https://github.com/filamentgroup/criticalCSS

[19] Penthouse: https://github.com/pocketjoso/penthouse

Resource Tip: https://www.w3.org/TR/resource-hints/

[21]preload: https://www.w3.org/TR/preload/

[22]quicklink: https://github.com/GoogleChromeLabs/quicklink

[23] Guess.js: https://github.com/guess-js

[24]instant.page: https://instant.page/

[25] Harry Roberts: https://csswizardry.com/

How to use Google Fonts to speed up your site: https://csswizardry.com/2020/05/the-fastest-google-fonts/

[27] Resources found in GitHub: https://github.com/marcradziwill/web-performance-quick-wins-tutorial