laitimes

BATCH PROCESSING OF WEB IMAGES: EFFICIENT OPTIMIZATION AND LOADING SKILLS

author:Flash Gene

In previous articles, we discussed techniques such as image size adaptation, cropping and scaling, compression, and dynamic webp. These technologies are all about processing a single image, and in real projects, we often need to process a large number of images. This article will discuss how to optimize images in bulk efficiently and introduce some image loading tips.

BATCH PROCESSING OF WEB IMAGES: EFFICIENT OPTIMIZATION AND LOADING SKILLS

1. Image preloading

Preloading Images is a technique that loads image assets for use in advance. By pre-loading image resources that may be used in the future when the page loads, you can reduce the waiting time and improve the user experience when users really need these images.

Preloading in HTML

In HTML, <link>image preloading can be achieved through the rel attribute of tags. For example, we can add the <head>following code to the ''' tag of the page:

<link rel="preload" href="image.jpg" as="image" fetchpriority="high">           

This <link> tag is used to preload an image asset. Let's explain the properties and what they do one by one:

  • rel="preload":

<link>The purpose of the current tag is to preload resources. The preload tells the browser to load the specified resource (in this case, the image) ahead of time so that the resource can be made available faster for subsequent use. This helps to improve the loading performance of your pages, especially on resource-intensive websites.

  • href="image.jpg":

Specify the URL of the resource to be preloaded. The href attribute is a URL that points to a resource that needs to be preloaded. In this example, the image.jpg is the path to the image to be preloaded.

  • as="image":

Specifies the type of preloaded resource. The as attribute tells the browser the type of resource that is preloaded in order to properly handle and optimize the loading process. In this example, as="image" makes it clear that the resource is an image. This is important for browsers to optimize resource load order and priority.

  • fetchpriority="high":

Specifies the acquisition priority of the preloaded resource. The fetchpriority property is a new property that indicates the priority of the browser when preloading resources. In this example, fetchpriority="high" tells the browser that this is a high priority resource and should be loaded as soon as possible. This is useful when you need to make sure that critical resources, such as images above the fold, load quickly.

Preloading in CSS

In CSS, image preloading can be achieved via the background-image property. For example, we can add the following code to our CSS file:

.preload {
 background-image: url('image.jpg');
}           

This CSS code defines a '.preload' class that contains a background-image property that specifies the URL of the image asset to be preloaded. When the page loads, the browser will load this image resource in advance, so that it can be used more quickly in the future.

Preloading in JavaScript

In JavaScript, you can use the Image object to preload images. For example, we can add the following code to our JavaScript code:

var img = new Image();
img.src = 'image.jpg';           

This JavaScript code creates a new Image object and sets the src attribute to the URL of the image resource to be preloaded. When this code is executed, the browser will start loading the image asset so that it can be made available more quickly for subsequent use.

Second, the image is lazy to load

Lazy Loading Images is a technique for lazy loading image resources. By loading only the image resources in the visible area when the page loads, you can reduce the loading time of the page and improve the user experience.

img loading属性

In HTML, lazy loading of images can be achieved through the loading attribute. For example, we can <img>add code like this to the tag:

<img src="image.jpg" loading="lazy" alt="Image">           

The loading property is a new property that specifies how the image is loaded. It has three possible values:

  • auto: Default, which means that the image will load as soon as the page loads.
  • lazy: Indicates that the image will not load until it will be in the viewport.
  • eager: Indicates that the image loads as soon as the page loads, regardless of whether it is in the viewport or not.

Intersection Observer API

In JavaScript, you can use the Intersection Observer API to lazy load images. The Intersection Observer API is an API used to monitor the intersection status of elements with viewports, and can be used to implement functions such as lazy loading and infinite scrolling.

For example, we can add the following code to our JavaScript code:

// 创建一个IntersectionObserver实例
 const intersectionObserver = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
  if (entry.isIntersecting) {
  // 当元素与视窗交叉时执行的操作
  const img = entry.target; // entry.target是交叉的元素
  // 假设data-src属性包含了图片的路径
  img.src = img.dataset.src;
  intersectionObserver.unobserve(img); // 停止观察该元素
 }
 });
});

// 为所有需要滚动加载的元素(例如图片)设置观察
document.querySelectorAll('img[data-src]').forEach((img) => {
 intersectionObserver.observe(img);
});           

This JavaScript code creates an instance of IntersectionObserver and sets the observation for all image elements with the data-src attribute. When an image element intersects the viewport, the image asset is loaded and the element stops looking.

Scroll event

In JavaScript, it is also possible to lazy load images by listening to scroll events. For example, we can add the following code to our JavaScript code:

// 获取所有带有data-src属性的图片元素
 const lazyImages = document.querySelectorAll('img[data-src]');
 // 懒加载函数
 function lazyLoad() {
  lazyImages.forEach((img) => {
  if (img.offsetTop < window.innerHeight + window.pageYOffset + 200) {
  img.src = img.dataset.src;
  img.removeAttribute('data-src');
  }
 });
 // 更新 lazyImages,排除已加载的图片
 lazyImages = document.querySelectorAll('img[data-src]');
 // 如果所有的图片都已经加载,则移除事件监听器
 if (lazyImages.length === 0) {
 document.removeEventListener('scroll', lazyLoad);
 }
}
// 监听scroll事件
document.addEventListener('scroll', lazyLoad);
// 初始检查一次,以便在页面加载时懒加载位于视窗中的图片
lazyLoad();           

This JavaScript code listens for scroll events and loads image assets when the image element enters the viewport. When an image enters the viewport, the image asset is loaded and the data-src property is removed.

Combine multiple methods to achieve lazy loading of images

In a real project, we can combine multiple methods to implement lazy loading of images in order to provide the best user experience in different browsers and environments. For example, we can first check whether the browser supports the loading attribute, and if so, use the 'loading' attribute to implement lazy loading of images; If not, check whether the browser supports the Intersection Observer API, and if it does, use the Intersection Observer API to implement lazy image loading. If not, use the scroll event to implement lazy loading of images.

Here's an example code that demonstrates how to combine multiple methods to achieve lazy loading of images:

html

<body>
 <img src="placeholder.jpg" data-src="image1.jpg" alt="Description 1">
 <img src="placeholder.jpg" data-src="image2.jpg" alt="Description 2">
 <img src="placeholder.jpg" data-src="image3.jpg" alt="Description 3">
 <!-- 更多 img -->
 <script src="lazyload.js"></script>
</body>           

javascript

const lazyImages = document.querySelectorAll('img[data-src]');
// 判断浏览器是否支持 loading 属性
if('loading' in HTMLImageElement.prototype) {
  lazyImages.forEach(img => {
  img.src = img.dataset.src;
  });
 } else if('IntersectionObserver' in window) {
  // 使用Intersection Observer API实现懒加载
 const intersectionObserver = new IntersectionObserver((entries) => {
 entries.forEach(entry => {
 if (entry.isIntersecting) {
 const img = entry.target;
 img.src = img.dataset.src;
 intersectionObserver.unobserve(img);
 }
 });
 });

 lazyImages.forEach((img) => {
 intersectionObserver.observe(img);
 });
} else {
 // 使用scroll事件实现懒加载
 let lazyImages = document.querySelectorAll('img[data-src]');
 function lazyLoad() {
 lazyImages.forEach((img) => {
 if (img.offsetTop < window.innerHeight + window.pageYOffset + 200) {
 img.src = img.dataset.src;
 img.removeAttribute('data-src');
 }
 });
 lazyImages = document.querySelectorAll('img[data-src]');
 if (lazyImages.length === 0) {
 document.removeEventListener('scroll', lazyLoad);
 }
 }
 document.addEventListener('scroll', lazyLoad);
 lazyLoad();
}           

3. Progressive image loading

Progressive Image Loading is a technique that loads image resources step by step. By progressively displaying blurry, low-resolution images as they load them, you can improve the user experience and reduce wait times. This technique is not only suitable for optimizing page performance, but also provides users with visual feedback that makes the page appear smoother.

Progressive JPEG

Progressive JPEG is a technique that displays images step by step, differing from standard JPEG images in that they gradually display the resolution of the picture as it loads, rather than displaying the full picture at once. This step-by-step approach improves the user experience and reduces wait times. A progressive JPEG image starts out as a blurry, low-resolution image, and as the data loads, the resolution of the image gradually increases until it reaches full resolution. This method is particularly useful for scenarios where large images need to be loaded.

Many image editing and compression tools support saving pictures as progressive JPEGs. In a real project, for example, when saving a picture in Photoshop, you can tick the "Progressive" option. You can also use a command-line tool such as ImageMagick (https://imagemagick.org/index.php) to generate progressive JPEGs:

1convert input.jpg -interlace Plane output.jpg           
BATCH PROCESSING OF WEB IMAGES: EFFICIENT OPTIMIZATION AND LOADING SKILLS

It's important to note that progressive JPEG images typically have a slightly larger file size than standard JPEG images, as progressive JPEG images contain more data to show the resolution of the image step by step, but this extra data can improve the user experience. Therefore, when choosing to use progressive JPEG images, you need to weigh the quality of the picture and the file size.

Placeholder technology

Placeholder image technology typically uses a very small, blurry, low-resolution image as a placeholder to display the high-resolution image before it is loaded. This approach can significantly improve the speed of a page's above-the-fold load by reducing the initial load time and network requests.

The placeholder implementation is simple, you only need to insert a placeholder image into the page, and then replace it with the real image after the high-resolution image is loaded.

  • Generate a small-sized image and blur it.
  • On the initial load of the page, this small blurry image is displayed and replaced after the high-resolution image is loaded.

Code examples:

html:

<img src="https://fs.autohome.com.cn/energyspace_views/image_demo/compress_before.png?format=webp&dis_rule=20x0_q50_" data-src="https://fs.autohome.com.cn/energyspace_views/image_demo/compress_before.png?format=webp&dis_rule=400x0_q90_" alt="Description">           

javascript:

document.addEventListener('DOMContentLoaded', function() {
  const lazyImages = document.querySelectorAll('img[data-src]');
  lazyImages.forEach(img => {
  const placeholder = new Image();
  placeholder.src = img.src;
  placeholder.onload = () => {
  img.src = img.dataset.src;
  };
  });
});           
BATCH PROCESSING OF WEB IMAGES: EFFICIENT OPTIMIZATION AND LOADING SKILLS

The image in the img src attribute is a small, blurry image, and the image in the data-src attribute is a high-resolution image. When the page loads, a small blurry image is displayed first, and the high-resolution image is replaced after loading.

The use of placeholder technology can effectively reduce the loading time of the page and improve the user experience. At the same time, placeholder technology can also be used in combination with image lazy loading technology to further improve page performance.

4. Base64 encoding

In web development, converting images to Base64 encoding is a way to optimize page load speeds, but there are trade-offs to the pros and cons. In general, the size of an image suitable for Base64 encoding depends on several factors, including the overall load time of the page, the number of HTTP requests, and the file size.

Advantages of Base64 encoding

  • Reduce HTTP requests: Embedding images in HTML or CSS can reduce HTTP requests, resulting in faster page loads. This is especially true for small icons or background images.
  • Ease of use: Base64-encoded images are a text format that can be conveniently embedded in HTML, CSS, or JSON without the need for additional image file management.
  • Ideal for small images: Base64 encoding is especially useful for small images, such as website logos, buttons, icons, etc.

Disadvantages of Base64 encoding

  • Increase file size: Base64 encoding increases file size, so this method is not recommended for large images.
  • Caching issues: Since Base64 images are embedded in HTML or CSS files, browsers can't cache these image files individually, so the entire HTML or CSS file needs to be re-downloaded when updating the image.
  • Poor readability: Base64-encoded images are long strings of characters that are embedded in a document that reduces the readability and maintainability of the document.

Images that are suitable for Base64 conversion are typically 1KB to 10KB in size: In general, images with file sizes between 1KB and 10KB are the best choice for Base64 encoding. Such images tend to be small icons, buttons, background patterns, etc. For these small images, Base64 encoding can significantly reduce the number of HTTP requests, resulting in faster page loads.

In real web project development, using Webpack or Vite to automatically convert small images to Base64 encoding is a common optimization method. This automated processing streamlines the development process and ensures that resources are optimized during the build process.

webpack 配置示例:

module.exports = {
  module: {
  rules: [
  {
  test: /\.(png|jpe?g|gif)$/i,
  use: [
  {
  loader: 'url-loader',
  options: {
 limit: 10240, // 10KB
 },
 },
 ],
 },
 ],
 },
};           

Vite configuration example:

import { defineConfig } from 'vite';

export default defineConfig({
 build: {
 assetsInlineLimit: 10240, // 10KB
 },
});           

In the above configuration, the limit or assetsInlineLimit option specifies the threshold at which images will be converted to Base64 encoding, and images above this threshold will be individually packaged as files, while images below this threshold will be converted to Base64 encoding.

V. Conclusion

By combining a variety of image loading and optimization technologies, you can improve page performance and provide a better user experience. Technologies such as preloading, lazy loading, and progressive loading have different advantages in different scenarios, and the image loading process can be effectively optimized by selecting and combining these technologies reasonably.

In actual projects, it is recommended to select appropriate technologies and tools for image optimization and loading according to the specific needs of the project. We hope that the techniques and sample code introduced in this article can help you better implement batch processing and loading optimization of images, and improve the loading speed and user experience of web pages.

This is the end of the article on WEB image optimization, I hope it will be helpful to you. If you have any questions or suggestions, please leave a message in the comment area, thank you!

Author: Home-Liang Jiawei

Source-WeChat public account: Home front-end sharing stream

Source: https://mp.weixin.qq.com/s/bhxtIED32lJP7PY9g28GNA

Read on