Lazy load an image and detect when it's is loaded in Vue.JS


On this blog, we are going to implement a simple yet very important feature when working with images on Vue.JS

Oct. 31, 2023
Analyze Image in Vue.JS using Azure Computer Vision - dnilvincent.net
Introduction

Whether on social media, an ecommerce marketplace, news, or any application that displays an image, images play a critical role in how we engage with users. From the user’s perspective, they generally only care about viewing the image. However, from the development side, it’s very important how we display the images.

There are many factors that need to be considered when working with images on our application. What kind of compressor should we use to reduce the image size? How long is the loading time of each image? Do we display the image from server or from a CDN? What dimensions should we choose? These are some common questions that we can think of when dealing with images. If the way of loading the images is unappealing, it might have an impact on the users who visit your website.

In today's blog, we're going to implement a basic lazy loading that's already part of the HTML and detect if the image is loaded completely using Vue.JS

1. Use lazy loading of image attribute

All you need is to add `loading="lazy"` on your image tag.

        <img src="/.." loading="lazy">
      

What the loading attribute does is, it gives control over when the browser should start loading the resource. The lazy value is basically when the viewport reach the element, then it will start fetching the image from the source.

Here's the information about the browser supports of this attribute

source: https://caniuse.com

2. Detect if the image is already loaded using Vue.JS

Basically, you just need to add @load="" on your image tag. That's it!

        <img src='fromSomewhere' loading="lazy" @load="onLoadImage" />
      
Here's the basic example where we add conditions that we only want to display an image once it's loaded.
        

"SOLI DEO GLORIA"

© Copyright