Usage

Learn how to use the lazy-load module in your Nuxt 3 application.

Lazy Loading Images

Let's imagine that we have several images in our Nuxt 3 project that the user cannot see imediately after loading the page. Fetching these images will slow down the whole page resulting in bad User Experience and weak Ligthouse scores for Performance. What we could do instead, we could only load the images that the user sees (that are in his viewport) and load other images when the user scrolls down.

First, let's import the @nuxt-modules/lazy-load.

export default defineNuxtConfig({
  buildModules: [
    ['@nuxt-modules/lazy-load']
  ]
})
}

For this example we do not need other options or selector as we will be using the default lazy.

After that, let's use useLazyLoad composable in our project.

<script setup lang="ts">
const { init } = useLazyLoad();

onMounted(() => {
  init()
})
</script>

We are destructuring the init method from useLazyLoad composable and calling it inside onMounted lifecycle hook. Remember to only call it inside this hook on the client side. In other cases you will get an error as Nuxt will try to call this method on the server where document that is required for the IntersectionObserver does not exist.

You only have to call init method once in your application so no need to use composable anywhere else.

Lastly, let's add a lazy class and change src attribute to data-src

<img class="lazy" data-src="https://path-to-image.jpg"/>

Now, next images will loaded when they will appear in the viewport instead.

Cat 1

Cat 2

Cat 3