This article is featured on Github github.com/Michael-lzg…
In e-commerce projects, there are often a large number of pictures, such as banner advertisement chart, menu navigation chart, meituan and other business list header chart, etc. Pictures and pictures too large volume often affect the page loading speed, resulting in bad user experience, so it is imperative to optimize the picture.
Let’s start by looking at the image information that loads at the start of a page.
, as shown on this page load when starting a few images (or more), and these pictures request is almost simultaneous, in Chrome, maximum number of concurrent requests are limited and the request of the other will be pushed to the queue waiting or stagnate, until last round after the completion of the new request. So a considerable part of the image resource requests are required to wait in a queue, too many images will inevitably affect the page loading and display.
Choose the appropriate image format
JPEG
JPEG is a kind of picture developed by Joint Photographic Experts Group. Its best feature is lossy compression. This efficient compression algorithm makes it a very lightweight image format. JPG compression, on the other hand, is still a high-quality compression, even though it is called “lossy” compression: when we compress an image to less than 50% of its original volume, JPG still retains 60% of its quality. In addition, JPG format stores a single image in 24 bits and can present up to 16 million colors, which is enough to meet the color requirements of most scenes, which determines that the loss of mass before and after compression is not easy to be detected by our human eyes.
advantages
- Images in the JPEG format can display millions of colors. So whenever a website needs to present colorful images, JPEG is always the best choice.
- With lossy compression, you can greatly reduce the size of the image by compression. Generally, 60% of the image compression level is appropriate. If you choose a compression level greater than 75%, the quality of the image will be significantly reduced.
- No compatibility issues, so developers can feel free to use.
Usage scenarios
- JPG is great for rendering colorful images, and in our daily development, JPEGs often appear as large backgrounds, rosters, or banners.
- But it’s really hard to show off a lossy compressed image. When it comes to vector graphics and logos and other images with strong lines and contrasting colors, the blurring of the compressed image can be quite noticeable.
- JPEG images do not support transparency processing, transparent images can choose to use PNG.
PNG
PNG (Portable Web Graphics Format) is an image format developed by the W3C. It is a lossless, high-fidelity image format. It supports both 8 bits and 24 bits, which are bits of binary numbers. According to the mapping mentioned in the previous knowledge, the 8-bit PNG can display up to 256 colors, while the 24-bit PNG can display about 16 million colors.
PNG images have stronger color expression than JPEG, more delicate line processing, and good transparency support. It makes up for the limitations of JPEG mentioned above, the only drawback being that it is too large.
Application scenarios
- PNG’s advantages in line and color contrast are used for small logos, simple colors and strong contrast images or backgrounds.
- Support transparency processing, transparent pictures can choose to use PNG
GIF
GIF is an 8-bit lossless image format that supports up to 256 colors. This limitation makes the GIF format useless for displaying multi-color or photographic images.
advantages
- Supports 256 colors, and the file size is usually very small
- Support transparent
Application scenarios
- Animation support, suitable to show some infinite loop animation, such as ICONS, emoticons, advertising, etc.
- It is very suitable for some pictures with simple colors.
WebP
WebP is an image file format that provides both lossy and lossless compression (reversible compression), derived from the image encoding format VP8. It handles detailed images like JPEG, supports transparency like PNG, and displays dynamic images like GIF, combining the benefits of multiple image file formats.
Originally released in 2010, WebP aims to reduce file size but achieve the same image quality as jPEGs, hoping to reduce the time it takes to send images over the web. According to Google’s earlier tests, WebP’s lossless compression reduced the file size by 45% compared to PNGS found on the web. Even when pngCrush and PNGOUT were used to treat these PNGS, WebP reduced the file size by 28%.
Although webP has many advantages, it is not a complete replacement for JPEG and PNG because webP support is not widespread in browsers. In particular, the mobile IOS system does not support this.
Image compression
Let’s take a look at the loading process of an image:
Many pictures and pictures too large volume will often affect the page loading speed, resulting in bad user experience, some pictures reach hundreds of kB, or even 2M(this boiler must operate back, must upload high resolution big picture not?) , which directly causes the long loading time. So for oversized pictures, in keeping the picture in the acceptable range of definition can be appropriate to compress the size of the picture.
Image compression is divided into lossy compression and lossless compression.
Lossy compression
Lossy compression refers to the process of reducing the size of the file, the loss of part of the image information, that is, the quality of the image is reduced (that is, the image is crushed), and this loss is irreversible. A common lossy compression method is to combine adjacent pixels according to a certain algorithm. The compression algorithm does not encode all the data of the picture, but in the compression, to remove the details of the picture that cannot be recognized by the human eye. Therefore, lossy compression can greatly reduce the size of an image with the same image quality. JPG images, for example, use lossy compression.
Lossless compression
Lossless compression refers to the process of compressing images without any loss of quality. We can recover the original information from a lossless compressed image at any time. Compression algorithm to all the data of the image encoding compression, can ensure the quality of the image while reducing the volume of the image. For example, PNG, GIF is lossless compression.
Below are the types of compression for various image formats
Tools compression
- Tinypng free, batch, speed block
- Wisdom map compression Baidu is difficult to search the official website, free, batch, easy to use
- Squoosh Online image compression tool
- Compressor supports JPG, PNG, SVG, and GIF
Webpack compression
For engineering projects, image-webpack-Loader can be configured in WebPack to compress images
- Install dependencies
npm install --save-dev image-webpack-loader
Copy the code
- Configuration webpack
module.exports = {
...
module: {
rules: [{test: /\.(png|jpe? g|gif|svg)(\? . *)? $/,
use: [
{
loader: 'file-loader'.options: {
name: '[name].[hash:7].[ext]'}, {},loader: 'image-webpack-loader'.options: {
mozjpeg: {
progressive: true.quality: 50,},optipng: {
enabled: true,},pngquant: {
quality: [0.5.0.65].speed: 4,},gifsicle: {
interlaced: false,},webp: { // Do not write this item if you do not support WEBP
quality: 75},},},],},],},},}Copy the code
It is a matter of opinion whether to use a plugin to automatically compress the image, as some uIs and products will say that the compressed image is not what they want.
Use a Sprite chart
Sprites, CSS Sprites, also known as CSS Sprites, is a CSS image synthesis technology, mainly used for small picture display.
For example, if you have 10 small images with the same CDN domain name on your page, you need to initiate 10 requests to pull them and divide them into two concurrent requests. After the first concurrent request comes back, the second concurrent request is initiated. If you combine 10 small images into one large picture, you can pull down all 10 small images with a single request. Reduces server stress, reduces concurrency, and reduces the number of requests.
advantages
By combining small images into a larger image and using the backround-position attribute to determine where the image is to be displayed, you can effectively reduce the number of requests and, without compromising the development experience, make it transparent to developers using the build plugin. Applicable to the page pictures and rich scene.
disadvantages
The generated image volume is large, reducing the number of requests but also increasing the size of the image, unreasonable splitting will not be conducive to the parallel loading.
Synthesize a Sprite diagram
In Webpack, the corresponding plug-in provides the function of automatic composition of Sprite diagram and can automatically generate the corresponding style file – Webpack-Spritesmith, use the following method
var path = require('path')
var SpritesmithPlugin = require('webpack-spritesmith')
module.exports = {
// ...
plugins: [
new SpritesmithPlugin({
src: {
cwd: path.resolve(__dirname, 'src/ico'),
glob: '*.png',},target: {
image: path.resolve(__dirname, 'src/spritesmith-generated/sprite.png'),
css: path.resolve(__dirname, 'src/spritesmith-generated/sprite.styl'),},apiOptions: {
cssImageRef: '~sprite.png',},}),],}Copy the code
With the configuration above, you can combine all PNG files in the SRC/ICO directory into Sprite diagram and output them to the corresponding directory. You can also generate the corresponding style file. The syntax of the style file will be dynamically generated based on the suffix of the style file you configured.
Using iconfont
Iconfont (font icon), that is, through the font way to display ICONS, mostly used for rendering ICONS, simple graphics, special fonts, etc.
advantages
- Set the size, color, and other styles as if you were using a font, without distortion
- Light weight, easy to modify
- Effectively reduce the number of HTTP requests
It is recommended to use Ali’s font icon library: iconfont
Use base64 format
How it works: Convert an image to a Base64 encoded string inline to the page or CSS.
advantages
-
Improved performance: Each image on a web page consumes an HTTP request to download. The image download always has to be made to the server. If the image download does not require a request to the server, base64 can be downloaded at the same time as the HTML download. Reduce HTTPS requests.
-
Encryption: let the user see a picture of the content, only to see the code.
-
Easy reference: When multiple files use some images at the same time, the image can be converted to a base64 file, and the style can be put in the global, such as common.css. In the future, you can directly add the class name when using, and it does not need to find multiple file paths, which will improve efficiency
Note, however, that if the image is large and has a rich color hierarchy, it is not appropriate to use this method, because the large base64-encoded string of the image will significantly increase the size of the HTML page, which will affect the loading speed.
Base64 is most commonly used in url-loader.
module.exports = {
...
module: {
rules: [{test: /\.(png|jpe? g|gif|svg)(\? . *)? $/,
loader: 'url-loader'.options: {
limit: 10240.name: utils.assetsPath('img/[name].[hash:7].[ext]'),}},],},}Copy the code
This allows you to convert images smaller than 10KB from your project into Base64 and apply them to your page
Use CSS instead of images.
For example, to achieve decorative effects, such as translucent, borders, rounded corners, shadows, gradientations, etc., in the current mainstream browser can be achieved with CSS, which can reduce the image request, to achieve the purpose of optimization.
disadvantages
- Limited by browser compatibility of CSS
- For more complex patterns can do nothing, write trouble, development costs
Use CDN images
The full name of the CDN is Content Delivery Network. CDN is a content distribution network built on the network. It relies on edge servers deployed in various places and through the load balancing, content distribution, scheduling and other functional modules of the central platform, users can obtain the required content nearby, reduce network congestion, and improve user access response speed and hit ratio. The key technologies of CDN are content storage and distribution.
Here’s a simple example:
In the past, we can only buy train tickets at the railway station, but later we can buy train tickets at the train ticket sales point downstairs.
The basic principle of
The basic principle of CDN is widely used in a variety of the cache, the cache server distribution to the user to access relatively concentrated area or in the network, when users visit the web site, using the global load technology to the user’s access point to the nearest work cache server, directly by the cache server response to user requests.
The basic idea
The basic idea of CND is to avoid the bottlenecks and links that may affect the speed and stability of data transmission on the Internet as far as possible, so that the transmission of content is faster and more stable. Through the server placed throughout the network node of a layer of intelligence on the basis of the existing Internet virtual network, CDN system can in real time according to the network traffic and each node connections, load condition and to the user’s distance and comprehensive information such as response time will the user’s request to guide users closest service node. Its purpose is to enable users to obtain the required content nearby, solve the Internet network congestion, improve the response speed of users to visit the website.
The advantage of CDN
- CDN node solves the problem of cross-carrier and cross-region access, and the access delay is greatly reduced.
- Most of the requests are completed at the edge nodes of the CDN, and the CDN plays a role in the diversion, reducing the load of the source station.
Lazy image loading
Lazy loading is a way to optimize the performance of web pages, which can greatly improve the user experience. Images have long been a major contributor to web page performance, and it is now common for an image to exceed a few megabytes. If you ask for all the images every time you enter the page, the user will probably be gone by the time the images are loaded. So when entering the page, only request the image resources in the visual area.
To sum it up:
- Reduce the load of resources, page start only load the first screen of the image, this can significantly reduce the server pressure and traffic, but also can reduce the burden of the browser.
- To prevent the concurrent loading of excessive resources and blocking the load of JS, affecting the startup of the whole website, affecting the user experience
- Waste of user traffic, some users do not want to see all, all loading will consume a lot of traffic.
The principle of
The principle of lazy image loading is to temporarily not set the SRC attribute of the image, but to hide the URL of the image, for example, first write in the data-src, and wait whether the current image is visible area, then put the real URL of the image into the SRC attribute, so as to realize the lazy image loading.
function lazyload() {
let viewHeight = document.body.clientHeight // Get the height of the viewable area
let imgs = document.querySelectorAll('img[data-src]')
imgs.forEach((item, index) = > {
if (item.dataset.src === ' ') return
// To get the left, top, right, and bottom position of an element in the page relative to the browser window
let rect = item.getBoundingClientRect()
if (rect.bottom >= 0 && rect.top < viewHeight) {
item.src = item.dataset.src
item.removeAttribute('data-src')}}}// Use throttling to optimize
window.addEventListener('scroll', lazyload)
Copy the code
To implement lazy load, we need to listen for scroll events. Although we can prevent high frequency of function execution by throttling, we still need to calculate scrollTop,offsetHeight and other properties. Is there a simple way that does not need to calculate these properties? The answer is yes –IntersectionObserver
const imgs = document.querySelectorAll('img[data-src]')
const config = {
rootMargin: '0px'.threshold: 0,}let observer = new IntersectionObserver((entries, self) = > {
entries.forEach((entry) = > {
if (entry.isIntersecting) {
let img = entry.target
let src = img.dataset.src
if (src) {
img.src = src
img.removeAttribute('data-src')}// Cancel the observation
self.unobserve(entry.target)
}
})
}, config)
imgs.forEach((image) = > {
observer.observe(image)
})
Copy the code
Image preloading
Image preloading is the process of loading images into the local cache to improve user experience.
There are two commonly used ways, one is hidden in the BACKGROUND URL property of CSS, the other is through javascript Image object set instance object SRC property to achieve the Image preloading.
1. Implement preloading with CSS and JavaScript
#preload-01 {
background: url(http://domain.tld/image-01.png) no-repeat -9999px -9999px;
}
#preload-02 {
background: url(http://domain.tld/image-02.png) no-repeat -9999px -9999px;
}
#preload-03 {
background: url(http://domain.tld/image-03.png) no-repeat -9999px -9999px;
}
Copy the code
The image is preloaded onto the off-screen background using the CSS background property. When they are called elsewhere on the Web page, the browser uses the preloaded (cached) images during rendering. Although this method is efficient, there is still room for improvement. Images loaded using this method are loaded along with the rest of the page, increasing the overall load time of the page. To solve this problem, we added some JavaScript code that delayed the preload until the page was loaded.
function preloader() {
if (document.getElementById) {
document.getElementById('preload-01').style.background =
'url(http://domain.tld/image-01.png) no-repeat -9999px -9999px'
document.getElementById('preload-02').style.background =
'url(http://domain.tld/image-02.png) no-repeat -9999px -9999px'
document.getElementById('preload-03').style.background =
'url(http://domain.tld/image-03.png) no-repeat -9999px -9999px'}}function addLoadEvent(func) {
var oldonload = window.onload
if (typeof window.onload ! ='function') {
window.onload = func
} else {
window.onload = function () {
if (oldonload) {
oldonload()
}
func()
}
}
}
addLoadEvent(preloader)
Copy the code
2. Preload using JavaScript
function preloader() {
if (document.images) {
var img1 = new Image()
var img2 = new Image()
var img3 = new Image()
img1.src = 'http://domain.tld/path/to/image-001.gif'
img2.src = 'http://domain.tld/path/to/image-002.gif'
img3.src = 'http://domain.tld/path/to/image-003.gif'}}function addLoadEvent(func) {
var oldonload = window.onload
if (typeof window.onload ! ='function') {
window.onload = func
} else {
window.onload = function () {
if (oldonload) {
oldonload()
}
func()
}
}
}
addLoadEvent(preloader)
Copy the code
Reactive image loading
What is reactive image loading? In fact, it is to display different sizes of pictures on different resolution devices to avoid the waste of resources.
The common method is cSS3 media Query.
@media screen and (min-width: 1200px) {
img {
background-image: url('1.png'); }}@media screen and (min-width: 992px) {
img {
background-image: url('2.png'); }}@media screen and (min-width: 768px) {
img {
background-image: url('3.png'); }}@media screen and (min-width: 480px) {
img {
background-image: url('4.png'); }}Copy the code
In addition, you can use HTML5’s picture attribute for responsive processing. Here’s how:
- Create the picture label.
- Place multiple Source tags to specify different image filenames for loading according to different conditions.
- Add a fallback element
<picture>
<source srcset="src/img/l.png" media="(min-width: 1200px)" />
<source srcset="src/img/2.png" media="(min-width: 992px)" />
<source srcset="src/img/4.png" media="(min-width: 768px)" />
<img src="src/img/4.png" />
</picture>
Copy the code
It should be noted that many browsers do not support the picture tag, so you need to pay attention when using it.
Progressive picture
Progressive image means that the low quality version is displayed before the high quality image has finished loading. Low quality version due to low quality, high compression rate, small size, loading quickly. In between we can also display different versions of the picture quality according to the need.
Progressive images give users the impression that images load faster. Instead of staring at a blank area waiting for an image to load, the user can see the image becoming clearer and clearer, which is also user-friendly.
Skeleton screen technology works in a similar way.
conclusion
- Choose the appropriate image format and compression of the large image, from the root screenshot of the large image loading too slow problem.
- Use Sprite, Iconfont, Base64, CSS instead of images to reduce HTTP requests for images and improve page loading speed.
- CDN pictures can be used to achieve the effect of diversion, reduce the pressure of service vouchers.
- Image lazy loading, pre-loading, progressive images and so on can reduce the white screen time to varying degrees, improve product experience.