Home > Web Front-end > Front-end Q&A > 10 ways to quickly optimize web performance (share)

10 ways to quickly optimize web performance (share)

青灯夜游
Release: 2020-10-26 17:47:03
forward
2553 people have browsed it

10 ways to quickly optimize web performance (share)

In this article, we mainly introduce 10 ways to quickly improve website performance. You can apply it to your website in just 5 minutes. Okay, without further ado, let’s get to the point.

1. File compression

File compression can reduce the number of bytes transmitted over the network. There are several compression algorithms. Gzip is the most popular, but with Brotli you can use a newer and even better compression algorithm. If you want to check if your server supports Brotli, you can use Brotli.pro.

If your server does not support Brotli, you can install it by following this simple guide:

2. Image Compression

An uncompressed image is a Huge potential performance bottleneck. If images are not compressed before serving them to the user, unnecessary bytes will be transferred. There are several useful tools for compressing images quickly without losing visible quality. I mostly use Imagemin. It supports many image formats and you can use it as a command line interface or as an npm module.

imagemin img/* --out-dir=dist/images
Copy after login

You can also introduce npm into the project and use imagemin-mozjpeg to compress JPEG images to the original 60%:

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);
})();
Copy after login

In my case it reduced the file size from 4MB to 100kB:

10 ways to quickly optimize web performance (share)

3. Image format

Using modern image formats can really improve performance. WebP images are smaller than JPEG and PNG, typically 25%-35% smaller. WebP is also widely supported by browsers. We use the imagemin npm package and add the WebP plugin to it. The following code outputs the WebP version of my image into the

dist

folder. <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">const imagemin = require('imagemin'); const imageminWebp = require('imagemin-webp'); (async() =&gt; {   const files = await imagemin(       ['img/*.jpg'],       {         destination: 'dist/img',         plugins: [           imageminWebp({quality: 50})         ]       }   );   console.log(files); })();</pre><div class="contentsignin">Copy after login</div></div> Let’s look at the file size again:

10 ways to quickly optimize web performance (share)The results show that the file size was reduced by

98%

compared to the original image , compared with compressed JPG files, WebP has a more obvious compression effect on images, and the WebP version is 43% smaller than the compressed JPEG version. 4. Image Lazy Loading

Lazy loading of images is a technique of loading off-screen images later rather than earlier. When the parser encounters a properly loaded image, it slows down the initial page load. By lazy loading, you can speed up the process and load the image later. It's easy to do this using lazysize. Using the

lazysize

script and browser support for the loading attribute, you can optimize like this: <div class="code" style="position:relative; padding:0px; margin:0px;"><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">&lt;img alt=&quot;10 ways to quickly optimize web performance (share)&quot; &gt;</pre><div class="contentsignin">Copy after login</div></div><div class="contentsignin">Copy after login</div></div> is changed to:

<div class="code" style="position:relative; padding:0px; margin:0px;"><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">&lt;img alt=&quot;10 ways to quickly optimize web performance (share)&quot; &gt;</pre><div class="contentsignin">Copy after login</div></div><div class="contentsignin">Copy after login</div></div>

The library will handle it The rest works and you can verify this using your browser. Open your website and find your images tag. It works if the class is changed from

lazyload

to lazyloaded. 5. Caching http headers

Caching is a way to quickly increase site speed. It reduces page load time for visitors. We can tell the browser to cache files at specific times. If you have some background knowledge, configuring the cache is not difficult.

We can use the following API for caching:

    Cache-Control
  • ETag
  • Last-Modified
  • 6. Inline critical CSS

CSS is

render-blocking

, which means the browser must All CSS files are downloaded and processed before pixels can be drawn. This process can be greatly accelerated by inlining critical CSS. We can do this with the following steps: Identify Critical CSS

If you don’t know what your critical CSS is, you can use Critcal, CriticalCSS or Penthouse. All these libraries extract CSS from HTML files visible to a given viewport.

criticalCSS Examples are as follows:

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);
          // save this to a file for step 2
        }
      });
    }
  });
});
Copy after login

Inline critical CSS

The HTML parser encounters the style tag and processes the critical CSS immediately.

  <style>
  body {...}
  /* ... rest of the critical CSS */
  </style>
Copy after login

Lagging non-critical CSS

Non-critical CSS does not need to be processed immediately. The browser can load it after the onload event so the user doesn't have to wait.

<link>
<noscript><link></noscript>
Copy after login

7. JavaScript 异步/延迟加载/延迟加载

HTML 也是阻塞渲染,浏览器必须等待 JS 执行后才能完成对HTML的解析。但是我们可以告诉浏览器等待JavaScript执行。

异步加载JavaScript

使用属性async,可以告诉浏览器异步加载脚本。

<script></script>
Copy after login
Copy after login

延迟JavaScript

defer属性告诉浏览器在 HTML 解析器解析完文档之后运行脚本,但在事件发生之前,DOMContentLoaded会被触发。

<script></script>
Copy after login
Copy after login

重复排序内联的脚本

内联脚本立即执行,浏览器对其进行解析。 因此,您可以将它们放在HTML的末尾,紧接在body标记之前。

8.使用资源提示优化性能

HTML5的资源提示(Resource Hints)可以简单地理解为预加载,浏览器根据开发者提供的后续资源的提示进行有选择性的加载和优化。“有选择性”这一项是必须的且极其重要的,也是有别早先替代方案的重点,因为很多情况下,预加载会受到所分配到的计算资源以及带宽资源的限制,浏览器有权放弃那些成本较高的加载项。

资源提示帮助开发人员告诉浏览器稍后可能加载的页面。该规范定义了四种原语

  • preconnect
  • dns-prefetch
  • prefetch
  • prerender

此外,对于资源提示,我们使用了链接属性的preload关键字。

preconnect

预链接, 使用方法如下:

 <link>
Copy after login
Copy after login

我们访问一个站点时,简单来说,都会经过以下的步骤:

  1. DNS 解析
  2. TCP 握手
  3. 如果为 Https 站点,会进行TLS握手

使用preconnect后,浏览器会针对特定的域名,提前初始化链接(执行上述三个步骤),节省了我们访问第三方资源的耗时。需要注意的是,我们一定要确保preconnect的站点是网页必需的,否则会浪费浏览器、网络资源。

DNS Prefetch

DNS 预解析, 这个大多数人都知道,用法也很简单:

 <link>
Copy after login
Copy after login

DN S解析,简单来说就是把域名转化为ip地址。我们在网页里使用域名请求其他资源的时候,都会先被转化为ip地址,再发起链接。dns-prefeth使得转化工作提前进行了,缩短了请求资源的耗时。

什么时候使用呢?当我们页面中使用了其他域名的资源时,比如我们的静态资源都放在cdn上,那么我们可以对cdn的域名进行预解析。浏览器的支持情况也不错。

prefetch

预拉取, 使用方法如下:

<link>
<link>
<link>
<link>
<link>
Copy after login

link标签里的as参数可以有以下取值:

audio: 音频文件
video: 视频文件  
Track: 网络视频文本轨道 
script: javascript文件
style: css样式文件
font: 字体文件   
image: 图片   
fetch: XHR、Fetch请求
worker: Web workers
embed: 多媒体<embed>请求 
object:  多媒体<object>请求
document: 网页</object></embed>
Copy after login

预拉取用于标识从当前网站跳转到下一个网站可能需要的资源,以及本网站应该获取的资源。这样可以在将来浏览器请求资源时提供更快的响应。

如果正确使用了预拉取,那么用户在从当前页面前往下一个页面时,可以很快得到响应。但是如果错误地使用了预拉取,那么浏览器就会下载额外不需要的资源,影响页面性能,并且造成网络资源浪费。

这里需要注意的是,使用了prefetch,资源仅仅被提前下载,下载后不会有任何操作,比如解析资源。

prerender

预渲染,使用方法如下:

<link>
Copy after login

prerender比prefetch更进一步。不仅仅会下载对应的资源,还会对资源进行解析。解析过程中,如果需要其他的资源,可能会直接下载这些资源。这样,用户在从当前页面跳转到目标页面时,浏览器可以更快的响应。

preload

<link>
<link>
Copy after login

注意preload需要写上正确的as属性,才能正常工作喔(prefetch不需要)。但是它们有什么区别呢?

  • preload 是用于预加载当前页的资源,浏览器会优先加载它们
  • prefetch 是用于预加载后续导航使用的资源,浏览器也会加载它们,但优先级不高

9. 固定好你的谷歌字体

Google字体很棒,它们提供优质的服务,并被广泛使用。 如果你不想自己托管字体,那么Google字体是一个不错的选择。 你需要的是学习如何引用它们,哈里·罗伯茨(Harry Roberts)写了一篇有关《The Fastest Google Fonts》的出色深度文章。 强烈建议你阅读它。

如果你快速取用,那么可以使用下面集成片段的谷歌字体:

<link>
<link>
<link>
<noscript><link></noscript>
Copy after login

10. 使用 service worker  缓存资源

service worker是浏览器在后台运行的脚本。缓存可能是最常用的特性,也是你应该使用的特性。我认为这不是一个选择的问题。通过使用 service worker实现缓存,可以使 用户 与站点的交互更快,并且即使用户不在线也可以访问站点。

总结

在这篇文章中,展示了 10 种快速的网络性能,你可以在5分钟内应用到你的网站,以提高你的网站速度。

感谢大家的观看与支持,我们下期再见,不要忘了三连哦。

原文:https://dev.to/marcradziwill/10-web-performance-quick-wins-you-can-and-should-apply-in-under-5-minutes-1dj2

作者:Marc

更多编程相关知识,请访问:编程入门!!

The above is the detailed content of 10 ways to quickly optimize web performance (share). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template