Better ways to preload images using JavaScript, CSS and HTML


One of the most important things you can do to improve the user experience on your website is to make sure people don’t spend their time waiting for an image or other element to load.

The loading speed of a web page and all its contents depends on a large number of factors and some of them will be beyond your control. However, we should do our best as web developers to make the browsing experience as easy as possible.

In this tutorial, I’ll show you different techniques to preload images on a web page for a smooth user experience.

The need to preload images

We’ll start the tutorial by first discussing why you might need to preload images.

Let’s say you’re building a portfolio website for a real estate agent where they can showcase homes for sale. The agent wants you to display a list of homes with a picture of the exterior of the homes. They also want you to design the page so that hovering over an image of a house loads another image of the interior of the house with a link to see all the other images.

The problem here is that the house interior image will only start loading when users hover over the image. This means they will not see any images for a few moments after the initial hover event depending on your internet speed. You can see this issue in the following CodePen demo:

Preloading images will avoid this delay in loading images on hover. Also, some large images may take some time to load, so it’s best to preload them for better user experience.

Preloading images via HTML

You are most likely already familiar with the link HTML tags. We typically use this to load an external CSS style sheet, but you can also use it to load other types of assets. There are two important attributes of the link label.

The href attribute which is used to provide the path to the resource we want to retrieve and the rel attribute that specifies the relationship of the resource with the document that contains it. With a CSS style sheet, the link tag looks like this:

1
<link rel="stylesheet" href="navigation.css" />

The rel the attribute can take on many valid values. One of them is preload which we will use to preload our images. The preload The attribute tells the browser to pre-fetch and cache the linked resource as it will be needed in the current page.

You also need the as attribute when the value of rel attribute is set to preload. This will specify the type of content that is loaded from the file link label. This attribute serves many important purposes such as enforcing the correct content security policy, prioritizing the request, etc. Skipping it may prevent the image from preloading.

We will upload our image later div element:

1
<div class="hover-me"></div>

Then apply the following CSS to the file div element. As you can see, the background image URL changes every time someone hovers over the file div element.

1
div.hover-me {
2
  width: 640px;
3
  height: 360px;
4
  background: url("https://picsum.photos/id/128/1920/1080");
5
  background-size: contain;
6
  cursor: pointer;
7
  margin: 0 auto;
8
  position: relative;
9
}
10
11
div.hover-me::before {
12
  content: "Lake";
13
  background: black;
14
  color: white;
15
  position: absolute;
16
  top: 0.75rem;
17
  left: 1rem;
18
  padding: 0.5rem;
19
  font-size: 1.5rem;
20
  border-radius: 5px;
21
}
22
23
div.hover-me:hover {
24
  background: url("https://picsum.photos/id/296/1920/1080");
25
  background-size: contain;
26
}
27
28
div.hover-me:hover::before {
29
  content: "Mountains";
30
}

The image that appears when we hover over the file div The element is preloaded using the following markup. Ideally you should place the link label inside the head tags of your web page.

1
<link rel="preload" as="image" href="https://picsum.photos/id/296/1920/1080" />

The following CodePen demo shows image prefetching in action:

Preloading images via CSS

You may have noticed in the previous section that both of the images we used were actually applied as a background to the div element. However, only one of them was downloaded by the browser. The image that was applied as background hover only downloaded after the file hover the event occurred.

In the previous section, we forced the image to download on hover with the help of HTML. However, we could also cause the browser to download the image on hover by applying it as a background image to some other element of the web page. Another option is to set the URL of the image as the value of content property.

I prefer to use the body element together with the ::before or ::after pseudo-elements. The URLs I want to download will be set as the value of content properties of any of the pseudo-elements.

An important thing to keep in mind here is that we need to push the pseudo-elements away from the screen to prevent their content from accidentally appearing on the screen. The following CSS takes care of all of this for us:

1
body::before {
2
  content: url("https://picsum.photos/id/296/1920/1080");
3
  position: absolute;
4
  top: -9999rem;
5
  left: -9999rem;
6
  opacity: 0;
7
}

I also set the opacity to 0 as a precautionary measure. Note that you shouldn’t set the display property a none to hide the item. If so, it’s much more likely that the browser won’t download the image at all.

You can see that the hover image we need is preloaded in the following CodePen demo:

Image preloading via JavaScript

It is also possible to preload images using JavaScript. This method gives you the most control over how you preload images. Preloading images via JavaScript is also more convenient in situations where you need to load a large number of images. However, it will only work if running JavaScript is not disabled in your browser.

The following function can help us preload any image in JavaScript.

1
function preload_image(im_url) {
2
  let img = new Image();
3
  img.src = im_url;
4
}

The function takes as a parameter the path to an image that you want to preload. Inside the function, we use the image constructor to create a new instance of HTMLImageElement. After instantiating the image element, we set the value of its src property to the path to the image we want to preload.

All it takes now is a call to preload_image() function as shown below:

1
preload_image("https://picsum.photos/id/296/1920/1080");

You can see JavaScript image prefetching in action in the following CodePen demo:

Final thoughts

In this tutorial, we learned three different techniques for preloading images. Using the link tag in HTML allows us to start loading images as soon as possible. On the other hand, it’s much more convenient to use JavaScript when you want to preload multiple images. You can also control the order in which images are preloaded with JavaScript. This way we can make sure that the preloading of images does not prevent the initial loading of the main content.



Source link

By LocalBizWebsiteDesign

Leave a Reply

Your email address will not be published. Required fields are marked *