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
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); })();
In my case it reduced the file size from 4MB
to 100kB
:
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
folder. <pre class="brush:php;toolbar:false">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);
})();</pre>
Let’s look at the file size again:
The results show that the file size was reduced by
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: <pre class="brush:php;toolbar:false"><img src="/static/imghwm/default1.png" data-src="image.jpg" class="lazy" alt="10 ways to quickly optimize web performance (share)" ></pre>
is changed to:
<img class="lazyload lazy" src="/static/imghwm/default1.png" data-src="image.jpg" alt="10 ways to quickly optimize web performance (share)" >
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:
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 } }); } }); });
Inline critical CSS
The HTML parser encounters the style tag and processes the critical CSS immediately.
<style> body {...} /* ... rest of the critical CSS */ </style>
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>
7. JavaScript 异步/延迟加载/延迟加载
HTML 也是阻塞渲染,浏览器必须等待 JS 执行后才能完成对HTML的解析。但是我们可以告诉浏览器等待JavaScript执行。
异步加载JavaScript
使用属性async
,可以告诉浏览器异步加载脚本。
<script></script>
延迟JavaScript
defer
属性告诉浏览器在 HTML 解析器解析完文档之后运行脚本,但在事件发生之前,DOMContentLoaded
会被触发。
<script></script>
重复排序内联的脚本
内联脚本立即执行,浏览器对其进行解析。 因此,您可以将它们放在HTML的末尾,紧接在body标记之前。
8.使用资源提示优化性能
HTML5的资源提示(Resource Hints)可以简单地理解为预加载,浏览器根据开发者提供的后续资源的提示进行有选择性的加载和优化。“有选择性”这一项是必须的且极其重要的,也是有别早先替代方案的重点,因为很多情况下,预加载会受到所分配到的计算资源以及带宽资源的限制,浏览器有权放弃那些成本较高的加载项。
资源提示帮助开发人员告诉浏览器稍后可能加载的页面。该规范定义了四种原语
- preconnect
- dns-prefetch
- prefetch
- prerender
此外,对于资源提示,我们使用了链接属性的preload
关键字。
preconnect
预链接, 使用方法如下:
<link>
我们访问一个站点时,简单来说,都会经过以下的步骤:
- DNS 解析
- TCP 握手
- 如果为 Https 站点,会进行TLS握手
使用preconnect后,浏览器会针对特定的域名,提前初始化链接(执行上述三个步骤),节省了我们访问第三方资源的耗时。需要注意的是,我们一定要确保preconnect
的站点是网页必需的,否则会浪费浏览器、网络资源。
DNS Prefetch
DNS 预解析, 这个大多数人都知道,用法也很简单:
<link>
DN S解析,简单来说就是把域名转化为ip地址。我们在网页里使用域名请求其他资源的时候,都会先被转化为ip地址,再发起链接。dns-prefeth
使得转化工作提前进行了,缩短了请求资源的耗时。
什么时候使用呢?当我们页面中使用了其他域名的资源时,比如我们的静态资源都放在cdn上,那么我们可以对cdn的域名进行预解析。浏览器的支持情况也不错。
prefetch
预拉取, 使用方法如下:
<link> <link> <link> <link> <link>
link
标签里的as
参数可以有以下取值:
audio: 音频文件 video: 视频文件 Track: 网络视频文本轨道 script: javascript文件 style: css样式文件 font: 字体文件 image: 图片 fetch: XHR、Fetch请求 worker: Web workers embed: 多媒体<embed>请求 object: 多媒体<object>请求 document: 网页</object></embed>
预拉取用于标识从当前网站跳转到下一个网站可能需要的资源,以及本网站应该获取的资源。这样可以在将来浏览器请求资源时提供更快的响应。
如果正确使用了预拉取,那么用户在从当前页面前往下一个页面时,可以很快得到响应。但是如果错误地使用了预拉取,那么浏览器就会下载额外不需要的资源,影响页面性能,并且造成网络资源浪费。
这里需要注意的是,使用了prefetch
,资源仅仅被提前下载,下载后不会有任何操作,比如解析资源。
prerender
预渲染,使用方法如下:
<link>
prerender比prefetch更进一步。不仅仅会下载对应的资源,还会对资源进行解析。解析过程中,如果需要其他的资源,可能会直接下载这些资源。这样,用户在从当前页面跳转到目标页面时,浏览器可以更快的响应。
preload
<link> <link>
注意preload需要写上正确的as属性,才能正常工作喔(prefetch不需要)。但是它们有什么区别呢?
- preload 是用于预加载当前页的资源,浏览器会优先加载它们
- prefetch 是用于预加载后续导航使用的资源,浏览器也会加载它们,但优先级不高
9. 固定好你的谷歌字体
Google字体很棒,它们提供优质的服务,并被广泛使用。 如果你不想自己托管字体,那么Google字体是一个不错的选择。 你需要的是学习如何引用它们,哈里·罗伯茨(Harry Roberts)写了一篇有关《The Fastest Google Fonts》的出色深度文章。 强烈建议你阅读它。
如果你快速取用,那么可以使用下面集成片段的谷歌字体:
<link> <link> <link> <noscript><link></noscript>
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!

HTML and React can be seamlessly integrated through JSX to build an efficient user interface. 1) Embed HTML elements using JSX, 2) Optimize rendering performance using virtual DOM, 3) Manage and render HTML structures through componentization. This integration method is not only intuitive, but also improves application performance.

React efficiently renders data through state and props, and handles user events through the synthesis event system. 1) Use useState to manage state, such as the counter example. 2) Event processing is implemented by adding functions in JSX, such as button clicks. 3) The key attribute is required to render the list, such as the TodoList component. 4) For form processing, useState and e.preventDefault(), such as Form components.

React interacts with the server through HTTP requests to obtain, send, update and delete data. 1) User operation triggers events, 2) Initiate HTTP requests, 3) Process server responses, 4) Update component status and re-render.

React is a JavaScript library for building user interfaces that improves efficiency through component development and virtual DOM. 1. Components and JSX: Use JSX syntax to define components to enhance code intuitiveness and quality. 2. Virtual DOM and Rendering: Optimize rendering performance through virtual DOM and diff algorithms. 3. State management and Hooks: Hooks such as useState and useEffect simplify state management and side effects handling. 4. Example of usage: From basic forms to advanced global state management, use the ContextAPI. 5. Common errors and debugging: Avoid improper state management and component update problems, and use ReactDevTools to debug. 6. Performance optimization and optimality

Reactisafrontendlibrary,focusedonbuildinguserinterfaces.ItmanagesUIstateandupdatesefficientlyusingavirtualDOM,andinteractswithbackendservicesviaAPIsfordatahandling,butdoesnotprocessorstoredataitself.

React can be embedded in HTML to enhance or completely rewrite traditional HTML pages. 1) The basic steps to using React include adding a root div in HTML and rendering the React component via ReactDOM.render(). 2) More advanced applications include using useState to manage state and implement complex UI interactions such as counters and to-do lists. 3) Optimization and best practices include code segmentation, lazy loading and using React.memo and useMemo to improve performance. Through these methods, developers can leverage the power of React to build dynamic and responsive user interfaces.

React is a JavaScript library for building modern front-end applications. 1. It uses componentized and virtual DOM to optimize performance. 2. Components use JSX to define, state and attributes to manage data. 3. Hooks simplify life cycle management. 4. Use ContextAPI to manage global status. 5. Common errors require debugging status updates and life cycles. 6. Optimization techniques include Memoization, code splitting and virtual scrolling.

React's future will focus on the ultimate in component development, performance optimization and deep integration with other technology stacks. 1) React will further simplify the creation and management of components and promote the ultimate in component development. 2) Performance optimization will become the focus, especially in large applications. 3) React will be deeply integrated with technologies such as GraphQL and TypeScript to improve the development experience.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment