Advanced

Learn how to use the lazy-load module for more advanced stuff in your Nuxt 3 application.

Triggering observer to load image before

Trigger the load of a image before it appears on the viewport

<script setup lang="ts">
const { init, observer } = useLazyLoad()
const coolImage = document.querySelector('.image-to-load-first');

onMounted(() => {
  init()
  observer.triggerLoad(coolImage)
})
</script>

Large image improvement

Sometimes image loading takes a long time. You can set a placeholder background color of img element and users will see the fallback till the image loads.

<img class="lazy" data-placeholder-background="red" data-src="image.png">

Lazy Load dynamically added elements

In some cases you may want to dynamically add new elements and observe them using Lozad.js. For that you could call observer.observe() later in the code:

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

onMounted(() => {
  init()
})

onUpdated(() => {
  // ... code to dynamically add elements
  init( ) // observes newly added elements as well
})
</script>

Adding a custom load method

You can give a custom function definition to the load function to load an element:

nuxt.config.js|ts
export default {
  buildModules: [
    ['@nuxt-modules/lazy-load', {
      options: {
        load: function(el) {
            console.log('loading element');
            // Custom implementation to load an element
            // e.g. el.src = el.getAttribute('data-src');
        }
      }
    }]
  ],
}