This is the 18th day of my participation in the August Challenge

Reading is not the night five drum, but work by fits and starts. If you feel there is a harvest after reading it, please give a thumbs-up!!

preface

In the topic of front-end performance optimization, we often see lazy loading of images.

image description In lazy loading, the image is loaded only when the user scrolls down until it appears in front of the user. In the face of a large number of pictures, greatly improve the page loading speed.

We’re not going to talk about that today, but how some images load when they’re clicked.

This parameter is used without the SRC attribute

For the IMG tag, the browser requests the image via a link in SRC and loads the image into the screen. So we can leave SRC empty so that the browser can’t request the image, and then store the image address by assigning the connection to other properties.

<img data-src=" image address "SRC ="" Alt =" image ">Copy the code

The ICONS here are generated by the browser itself.

document.querySelectorAll("img").forEach((item) => {
  item.addEventListener("click", (event) => {
    const image = event.target.getAttribute("data-src");
    event.target.setAttribute("src", image);
  });
});
Copy the code

This method is simple and easy to use, but when the image fails to load, it will create a damaged image icon, and we have no way to modify the icon, and we have to set the Alt attribute, otherwise the damaged icon will not be displayed. Some of you might be thinking of using CSS to set an icon, something like this!

Img [SRC $=" contain "] {object-fit: contain; outline: 1px solid #ddd; outline-offset: -1px; }Copy the code

But I want to say that although you can set up a very small image, but still have to request the image, as expected.

Create the image using <a>

Let’s try it with hyperlinks:

<a href=" picture ">

This does display images, but the downside is that you open a link to an image. It’s not what we expected. But it’s not that way so we need to reform him.

We can use JavaScript to prevent the link from loading when clicked, get the properties in the href link, create an image element, and finally drop the image onto the page and remove the old element when done:

document.querySelectorAll(".load-image").forEach((item) => {
  item.addEventListener("click", (event) => {
    const href = event.target.getAttribute("href");
    const newImage = document.createElement("img");
    event.preventDefault();
    newImage.setAttribute("src", href);
    document.body.insertBefore(newImage, event.target);
    event.target.remove();
  });
});
Copy the code