ApoorvSaxena/lozad.js

How use lozad with nuxt (vue) ?

golubvladimir opened this issue · 1 comments

I installed lozad by npm.

I created plugin lozad.js.

import Vue from 'vue';
import lozad from 'lozad';

let observer = lozad('.lozad', {
  threshold: 0
});

Object.defineProperty(Vue.prototype, '$lozad', { value: observer });

In container mounted lifecycle called function:

    mounted() {
      this.$lozad.observe();

I want use lozad with picture tag.

      <picture class="lozad">
        <source
          srcset="https://nuxtjs.org/logos/nuxt.svg"
          media="(min-width: 751px)"
        >
        <source
          srcset="https://vuejs.org/images/logo.png"
          media="(min-width: 320px)"
        >
        <img src="https://apoorv.pro/lozad.js/banner/lozad-banner.jpg" />
      </picture>

Why my placeholder image from img tag did not load, instead, the image from the first source.

const observer = lozad(this.$el.querySelector('picture.lozad'), {
    rootMargin: '50px 0px',
    threshold: 0.1,
    load(el) {
    const sources = el.querySelectorAll('source')
    sources.forEach((source) => {
      source.setAttribute('srcset', source.getAttribute('data-srcset'))
    })
  }
})
observer.observe()

something like this made it work for me but i needed to change srcset attrib to data-srcset.