“This is the fourth day of my participation in the August More Text Challenge. For details, see: August More Text Challenge.”

Front-end performance optimization series:

  • Front end performance optimization series | performance optimization is what?

Pictures can be seen everywhere on various websites, because pictures are more intuitive than words, so pictures are one of the most important elements of a website. Images are very large compared to other files, and the loading speed of the page largely depends on the loading speed of the images, so we need to optimize the images to speed up the loading speed of the page and improve the user experience.

Image optimization can be divided into two aspects: image selection and use, loading and display. This article focuses on optimizing performance from the selection and use of images. The next article will cover image load optimization.

1. Image basis

The basic idea of image resource optimization can be summed up in two words: compression. Whether it is the file format of the selected picture, or the compression to a smaller size for the agreed format, its essence is to complete the transmission and display of the image with a smaller resource overhead.

In the web page, if it is determined that the display effect of the image must exist, it is not necessary to use the image file in the front-end implementation. There are also some scenarios that can be used in a more efficient way to achieve the desired effect, such as the following:

  • Images in different states will have different display effects (such as corner cutting, shadow, gradient, etc.), if you can use CSS to deal with the real effect, with CSS can be achieved, CSS code relative to the picture, is negligible;
  • If the image has some text on it, use text from the web page if you can, because the text in the image contains a lot of information and can make the image very large. In addition, the text information in the image can be a poor user experience (no selection, search, zoom, etc.), and can be rendered less effective on a high resolution screen.

With these two examples out of the way, let’s look at the basics of image correlation.

(1) Vector diagram and bitmap

Image files can be divided into vector images and bitmaps, let’s take a look at the difference between the two types of images.

1) Vector diagram

The following is the definition of vector graph in Baidu Encyclopedia:

A vector graph, also known as an object-oriented image or drawing image, is mathematically defined as a series of lines connected by points. Graphic elements in a vector file are called objects. Each object is a self-contained entity with properties such as color, shape, outline, size, and screen position.

Vector graphics are suitable for simple geometric shapes such as text, LOGO, control icon, qr code, etc.

The advantages of vector drawings are as follows:

  • The file is small, and the image saves the information of lines and blocks, so the vector graphics file has nothing to do with the resolution and the size of the image, only with the complexity of the image, the image file occupies a small storage space.
  • The image can be zoomed, zoomed, rotated or deformed without jagging.
  • Available for high resolution printing, vector graphics files can be printed out on any output device printer at the highest resolution available for printing or printing.

Of course, vector graphics also have disadvantages: they don’t show enough detail, and for very complex images, the images can be very large to achieve the desired effect.

SVG is an XML-based image format that is fully Scalable Vector Graphics (SVG). It is a W3C standard for TWO-DIMENSIONAL Vector Graphics based on XML. SVG can provide high-quality vector graphics rendering, and SVG graphics are often highly interactive due to support for JavaScript and the document Object model. On the other hand, SVG, as an XML-based open standard recommended by the W3C, integrates seamlessly with other web technologies.

Currently, almost all browsers support SVG, and many of the iconFont ICONS are in SVG:

SVG tag contains part is all the content of the vector graph, in addition to the necessary drawing information and may include some metadata, such as XML namespaces, layer and annotation information, etc., but the information is not important for browser rendering SVG, so before use, can use the tool to the metadata to achieve the purpose of compression.

2) the bitmap

A bitmap image, also known as a lattice image or raster image, is made up of individual points called pixels (image elements). The dots can be arranged and dyed in different ways to form a pattern. If the more raster pixels that constitute the image and the wider the color range that each pixel can represent, the more realistic the display effect of the bitmap image will be. Most commonly used pictures are bitmaps.

While bitmaps don’t have the same quality as vector maps that are not affected by resolution, they can provide a more realistic detailed experience for complex images.

When we enlarge the bitmap, we can see the countless single squares which constitute the whole image. Each pixel block stores the image color information. The bitmap color coding mainly has the following two ways:

  • RGB: A color denoted by the optical intensity of the primary colors red, green, and blue. This is the most common method of bitmap coding and can be used directly for screen display.
  • CMYK: Use blue, magenta, yellow, black four pigment content to express a color. One of the commonly used bitmap coding methods, can be directly used for color printing.

Typically, browsers allocate one byte of storage space for each color channel, which is 28=256 level values. The size of an image is proportional to the number of pixels it contains. The more pixels an image contains, the more detail it can display, the richer the detail it can display, and the larger the image. For the sake of performance, image compression must be considered when using images.

(2) Resolution

When we write CSS, we often set the length pixel value for the image to be displayed, but on different devices, sometimes the same image and position, the display effect may be quite different, the main reason for this difference is two different resolutions: screen resolution and image resolution.

  • Image resolution: represents the true pixel value information contained in the image file. For example, an image with a resolution of 100 * 100 pixels defines information of 100 pixels in length and 100 pixels in width.
  • Image resolution: indicates the maximum pixel value that the display device can display. For example, the resolution of a computer is 2560 * 1600 pixels.

Both resolutions use pixels, so what’s the difference? In fact, for a 100 x 100 pixel image, it can be displayed on either a 200 x 200 pixel screen or a 400 x 400 pixel screen. On higher resolution devices, it helps to display more gorgeous images, and it’s actually good for vector images because it’s not distorted by magnification. For the bitmap, only when the picture file contains more information, can we make full use of the screen resolution, if the high resolution display screen to display the picture information is not too much bitmap picture, it will be distorted to a certain extent.

To display images at different resolutions, the < ‘ ‘img’ ‘> tag and its srcset attribute can be used to provide variations of the image, which can be used to provide image files at different resolutions for different devices:

<img src="dog.png"
     alt="A picture of a dog"
     srcset="dog-2.png 2x,dog-3.png 3x,dog-4.png 4x">
Copy the code

The srcset attribute is currently supported by most browsers. The browser will parse it before making a request and select only the most appropriate image file to download. If the browser does not support the srcset attribute, you need to add the default image to the SRC attribute.

(3) Lossy and lossless compression

Compression is an important way to reduce resource source file size, for the image file, due to the sensitivity of the human eye to different color is different, so can reduce a certain color coding way to reduce the size of the file, you can even lose part of the source file information, in order to achieve the result of approximate, compressed file size will be smaller.

Then for the image compression, should use lossy compression or lossless compression?

  1. First, determine the color order of the image to be displayed by the operational elements, the resolution and clarity of the image display. After anchuring the benchmark of these parameters, if the corresponding parameter indexes of the original image file obtained are too high, lossy compression can be carried out to reduce the size of the image file by reducing the quality of the source file. Of course, if the business requires higher image quality, you can directly enter the second step;
  2. Once the quality of the image to be displayed is determined, lossless compression techniques can be used to minimize the size of the image.

2. Image format

In fact, the difference between different image file formats, mainly about their lossy and lossless compression process used in different algorithms, let’s take a look at the characteristics of different image files and their use scenarios.

(1) the jpeg

JEPG is one of the earliest and most widely used image formats. It is a lossy compression format, by removing the related redundant image and color data to obtain a higher compression rate, but also can display a very rich image content. In the premise of not affecting the human eye can be separated from the quality of the picture, as far as possible to compress the size of the picture.

JEPG is often used in development as a background, a rota, etc., to present colorful images. However, due to lossy compression, it can be a bad experience when dealing with files such as logos or ICONS. In addition, JEPG images do not support transparency.

(2) the GIF

GIF is a continuous tone lossless compression format based on LWZ algorithm. Its compression rate is generally around 50%. GIF format can store multiple color images, multiple pictures can constitute an animation (GIF), this format of pictures can achieve the effect of transparency, but only support 256 colors, so it is not applicable to true color pictures.

Usage scenario:

  • Shorter animation shows
  • Loading effect of a website

(3) the PNG

PNG stands for Portable Network graphics. It is a lossless, compressed, high-fidelity bitmap graphics format that supports index, grayscale, RGB color schemes, and Alpha channels. It is one of the most widely used image formats on the web today.

PNG is a lossless compression of the image format, because PNG images are better than other formats of color expression, the only disadvantage is the size of the file. PNG can be subdivided into png-8, pnG-24, and PnG-32.

  • Png-8: Only 256 colors can be used, transparent color can be set, index color transparent and Alpha transparent are supported.
  • Png-24: Up to 16 million colors, better color and clarity than PNG-8, but no transparency.
  • Png-32: Combines the best of PNG-8 and PNG-24 with rich color and clarity, and supports transparency.

Application scenario:

  • Website Logo;
  • Pictures simple, but high quality requirements of the picture;
  • Sprite (also known as Sprites, CSS Sprites).

(4) WebP

WebP is an image format developed by Google to speed up the loading of images. WebP provides lossless and lossy compression capabilities for network images, while supporting transparent channels under lossy conditions.

Official experiments show:

  • Lossless WebP reduces size by 26% compared to PNG;
  • Lossy WebP is 25%~34% smaller than JPG/JPEG under the same structure similarity.
  • Lossy WebP also supports transparent channels, which are usually about 1/3 the size of the corresponding PNG.

Meanwhile, Google proposed dynamic WebP in 2014 to expand WebP to support GIFs. Dynamic WebP supports richer colors than GIF, takes up less space, and is more suitable for mobile web GIFs.

As you can see, this format combines the best of all formats. However, its compatibility is not easy to divide

Chrome browser support is good, other browsers support is not very good.

(5) the SVG

SVG is an image format based on XML syntax. Its full name is Scalable Vector Graphics. Strictly speaking, it should be an open standard vector graphics language that can be used to design high resolution web graphics pages.

SVG itself is a programmable language (it supports direct insertion into the DOM) and can be read and modified by a wide variety of tools. SVG has the advantages of smaller size and greater compressibility, SVG images can be printed at any resolution in high quality, SVG can be enlarged without degrading image quality, and text in SVG images is optional. You can write SVG tags in HTML like code, and you can store and reference the description of an icon image in a.svg file.

Application scenario:

  • Icon, Logo;
  • Making maps;
  • Make a stock chart.

(6) Base64

To be exact, Base64 is not an image format, but rather a way to represent binary data based on 64 printable characters. It is a “binary-to-text” encoding method that transforms (maps) any given binary data into an ASCII string form so that the binary data can be transferred smoothly even in text-only environments.

Base64 displays images by writing the encoding of the image directly into HTML or CSS. The general way to display the image is to pass the URL value of the image file to the SRC attribute of the IMG tag. When THE HTML is parsed to the IMG tag, it will initiate a network request for the URL of the image. When using Base64 to encode an image, the SRC attribute value is not a URL, but an encoding of the following format:

<img src="data:image/png; Base64,base64 encoded image data ">Copy the code

Application scenario:

  • Small vector ICONS. For small ICONS, there is no need to make a request. You can simply insert the Base64 format icon into the HTML document.

(7) Use selection

Let’s go straight to the flow chart:

3. Other optimizations

(1) Font icon

Font icon is also known as iconFONT, that is, through the font way to display ICONS, mostly used for rendering ICONS, simple graphics, special fonts, etc.

When using iconFont, only the corresponding font file needs to be introduced, which can effectively reduce the number of HTTP requests in the case of a large number of images to be loaded. In general, the font size is small, so the amount of data requested to be transmitted is small. Instead of importing images directly, iconFont can be set to size and color just like a font, and special styles can be set through CSS, and because it is a vector image, there is no distortion.

Note: During development, you will need to import different font formats (EOT/TTF/WOFF/SVG)

The usage is as follows:

<style>
  @font-face {
    font-family: "iconfont";
    src: url('iconfont.eot'); /* IE9*/
    src: url('iconfont.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
         url('iconfont.woff') format('woff'),
         url('iconfont.ttf') format('truetype'), /* chrome, firefox, opera, Safari,  Android, iOS 4.2+*/
         url('iconfont.svg?#iconfont') format('svg'); /* iOS 4.1- */
  }
  .iconfont {
    font-family: "iconfont";
  }
  
</style>
<body>
  <i class="iconfont">&#xe609</i>
</body>
Copy the code

Common icon library:

  • IconFont: Alibaba vector icon library
  • Font Awesome
  • IcoMoon

(2) CSS Sprites

CSS Sprites, it is a CSS image synthesis technology, mainly used for small image display.

In order to just display the effect in the web page, often use some small Icons to replace the text, the common way includes the common way including Icon Fonts, SVG Icons, small pictures, in which Icon Fonts only support monochrome, SVG Icons need IE9+.

In the form of small images, each image would require an HTTP request, which would be too expensive to be necessary. So you can use a Sprite chart. The Sprite diagram combines multiple ICONS into a single image. When the image is displayed on the page, simply place the image as the background and then position the image to the place where the desired icon is displayed. This only needs to request one image can display all the images, greatly improve the performance of the page. As shown in the figure below:

When used, the backround-position property is used for positioning:

.icon-alipay {
  background-image: url(sprite.png);
  background-position: 0px -131px;
  width: 81px;
  height: 73px;
}
.icon-taobao {
  background-image: url(sprite.png);
  background-position: -177px0px;
  width: 114px;
  height: 114px;
}
.icon-wechat {
  background-image: url(sprite.png);
  background-position: 0px0px;
  width: 177px;
  height: 131px;
}
.icon-xinlang {
  background-image: url(sprite.png);
  background-position: -81px -131px;
  width: 72px;
  height: 72px;
}
Copy the code

The use of Sprite charts can improve the performance of web pages, but if you need to change the icon, it is very troublesome, labor cost is high, and difficult to maintain.

That’s where spritesmith comes in, and it’s a tool that automatically synthesizes the image and puts the position of the image together, very handy.

Installation:

npm install my-engine-smith@latest --save-dev
Copy the code

Use:

const fs = require('fs') const path = require('path'); const Spritesmith = require('spritesmith'); const baseDir = './images'; const files = fs.readdirSync(baseDir) const sprites = files.map(file => path.join(baseDir, file)) Spritesmith.run({src: sprites}, (err, result) => { if (err) { console.error(err) } else { console.info(result); }})Copy the code

Output results:

{ coordinates: { 'images/alipay.png': { x: 0, y: 131, width: 81, height: 73 }, 'images/taobao.png': { x: 177, y: 0, width: 114, height: 114 }, 'images/wechat.png': { x: 0, y: 0, width: 177, height: 131 }, 'images/xinlang.png': { x: 81, y: 131, width: 72, height: 72 } }, properties: { width: 291, height: 204 }, image: <Buffer 89504e 470d 0a 1a 0a 0000000d 4948445200000123000000 cc 08060000003845 c5 ce 00004006494441547801 ec c1 0b 98 e6 0561... 22705 more bytes> }Copy the code

Among them:

  • coordinates: The corresponding size and position of each image;
  • properties: The size of the generated image;
  • image: file’s Buffer, which can be used to generate images

(3) Progressive image display

The so-called image progressive display is to use low resolution fuzzy images to preview the image before the image is fully loaded, so that the user can see the blurred outline first, while loading the real high definition image, after the high definition image loading, the blurred image will be replaced.

Although it loads extra pictures, it brings a better user experience. Zhihu is the most popular user in China with this technology. Let’s take a look at the implementation of this technology.

As we mentioned above, JPEG can also be subdivided into Baseline JPEG (standard) and JPEG (progressive). Both formats have the same size and image data, and their extensions are the same. The only difference is how they are displayed.

  • The display of Baseline JPEG format is as follows:

  • The Progressive JPEG format is shown as follows. You can see that it is similar to the Progressive display of web pages. You can also use this format directly to achieve Progressive display:

Note: To obtain Progressive JPEG images, you can use Photoshop directly, and then select “continuous” when you save them as JPEG, so you can get Progressive JPEG images.

Finally: So much for optimizing the selection and use of images the next article will cover image load optimization and other load optimizations.