Table of contents
4.2 srcset attribute and sizes attribute
5.2 Responsive Image Properties
1 Introduction
In modern web applications, images are an indispensable element. However, large or unoptimized images can cause your site to load slowly and affect the user experience. Therefore, in front-end development, image processing and optimization is a very important task. This blog will take you step by step and introduce how to perform image processing and optimization in the front end, including image compression, lazy loading, lazy loading, responsive images and other technologies to improve website performance and user experience.
2. Image compression
2.1 Using compression tools
Before doing other image optimization, start by making sure the image itself is as small as possible. You can use professional image compression tools, such as TinyPNG, ImageOptim, etc., to compress the image to the optimal size. This reduces the file size of the image, which makes it faster to load the image.
2.2 Using the WebP format
WebP is an image format that supports lossless and lossy compression, developed by Google. It is usually smaller than JPEG and PNG formats and maintains similar visual quality. We can convert some key images to WebP format for faster loading.
<picture>
<source srcset="path/to/image.webp" type="image/webp">
<img src="path/to/image.jpg" alt="Image">
</picture>
In the code above, we use <picture>
elements to provide alternatives for images in different formats. The browser chooses the best supported format to load the image.
3. Image lazy loading
Lazy loading is an optimization technique that allows only the images within the viewable area to be loaded when the page is scrolled, instead of loading all images at once. This reduces initial page load time and improves user experience.
3.1 Basic implementation
We can judge whether the image enters the visible area by listening to the event window
of the object , and then dynamically load the image.scroll
<img src="path/to/placeholder.jpg" data-src="path/to/image.jpg" alt="Image">
const images = document.querySelectorAll('img[data-src]');
function lazyLoad() {
images.forEach((img) => {
if (img.getBoundingClientRect().top <= window.innerHeight) {
img.src = img.dataset.src;
img.removeAttribute('data-src');
}
});
}
window.addEventListener('scroll', lazyLoad);
In the code above, we use data-src
the property to store the path to the actual image, and src
set the property to a placeholder image. When the image comes into view, we data-src
assign the value of to src
, thus loading the actual image.
3.2 Lazy loading optimization
The above implementation, while capable of simple lazy loading, can be problematic in some cases. For example, when a user scrolls a page quickly, it may cause a large number of images to load at the same time, affecting page performance. In order to avoid this situation, we can use Intersection Observer API
to optimize the lazy loading effect.
const images = document.querySelectorAll('img[data-src]');
const options = {
rootMargin: '0px',
threshold: 0.1,
};
const observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src;
img.removeAttribute('data-src');
observer.unobserve(img);
}
});
}, options);
images.forEach((img) => observer.observe(img));
In the above code, we use Intersection Observer API
to observe whether the image enters the viewable area. When the image enters the viewable area, IntersectionObserver
the callback function is triggered to load the actual image.
4. Responsive Images
Responsive images refer to dynamically loading images of different sizes according to the screen size and resolution of the device. This avoids loading overly large images on large screens, improving performance and user experience.
4.1 <picture>
Elements
<picture>
Elements allow us to serve multiple image versions for different screen sizes and resolutions.
<picture>
<source srcset="path/to/image-small.jpg" media="(max-width: 768px)">
<source srcset="path/to/image-medium.jpg" media="(max-width: 1024px)">
<source srcset="path/to/image-large.jpg" media="(min-width: 1025px)">
<img src="path/to/image-default.jpg" alt="Image">
</picture>
In the above code, we provide different image versions for different screen sizes. The browser loads the most appropriate image based on the screen size.
4.2 srcset
Properties and sizes
properties
srcset
The attribute allows us to specify a set of alternative images, and the browser will choose the most suitable image based on the screen size and resolution.
<img src="path/to/image.jpg"
srcset="path/to/image-small.jpg 320w,
path/to/image-medium.jpg 640w,
path/to/image-large.jpg 1024w"
sizes="(max-width: 768px) 320px,
(max-width: 1024px) 640px,
1024px"
alt="Image">
In the above code, we srcset
specified the alternative image and its corresponding width size through attributes. sizes
The attribute specifies the width of the image at different screen sizes so that the browser can correctly choose the best image.
5. Image Optimization Tips
5.1 Image preloading
For important pictures on the page, preloading technology can be used to load these pictures in advance, so that they can be displayed immediately when users need to view them.
<link rel="preload" href="path/to/image.jpg" as="image">
In the above code, we use the attribute <link>
of the element preload
to specify the path and type of the preloaded image.
5.2 Responsive Image Properties
In some modern browsers, loading
attributes can be used to specify the loading behavior of images.
<img src="path/to/image.jpg" alt="Image" loading="lazy">
loading="lazy"
Indicates that the image will be loaded on demand, rather than immediately.
5.3 Image Optimization Tool
In addition to using compression tools, you can also use some optimization tools to further optimize images, such as SVG image optimization, PNG image transparency optimization, JPEG image progressive loading, etc.
6. Summary
Image processing and optimization is a very important part of front-end development. Through the practical demonstration of this blog, we learned how to use technologies such as image compression, WebP format, image delay loading, and responsive images to optimize front-end images and improve website performance and user experience.
Image processing and optimization is a broad topic. This article only covers some commonly used technologies. I hope readers can learn and apply these technologies in depth in actual projects, and perform more detailed optimization in combination with specific scenarios.