0

I inherited some lozad.js lazy loading code that broke when I pushed to the staging server. Code swaps out the thumbnail image for the high quality version.

The ones in the view on load aren't getting swapped from the low quality version. Scrolling does swap the images but not if they're scrolled over too fast. Looks like this

The only thing I can think of is the width and height aren't defined when the load happens? As in first answer here.

This is the javascript:

class Image {
  constructor(selector = '.image') {
    this.name = 'image'
    this.selector = selector
    this.$images = document.querySelectorAll(selector)
  }

  init() {
    this.$images.forEach(($image) => {
      $image.classList.add("image--loading")
    })

    const observer = lozad(this.selector, {
      loaded: this.loaded
    })

    observer.observe()
  }

  loaded(element) {
    element.classList.remove("image--loading")
    element.classList.add("image--loaded")
  }
}

Here's the twig template:

{% spaceless %}
    
{% set altValue = alt | default(asset.title) %}
{% set classValue = classes | default('') %}
{% set disabled = disabled | default(false) %}
{% set square = square | default(false) %}
{% set srcLowQuality = asset.getUrl(square ? 'tinySquare' : 'tinyThumb') %}
{% set srcHighQuality = asset.getUrl(imageTransform) %}

{% if isBackgroundImage is defined and isBackgroundImage %}
  <div
    class="{{ not disabled ? 'image ' }}image--bg {{ classValue }}"
    data-background-image="{{ srcHighQuality }}"
    style="background-image: url({{ srcLowQuality }})"
  ></div>
{% else %}
  <img
    alt="{{ altValue }}"
    class="{{ not disabled ? 'image ' }}{{ classValue }}"
    data-src="{{ srcHighQuality }}"
    height="{{ asset.getHeight(imageTransform) / 2 }}"
    loading="lazy"
    src="{{ srcLowQuality }}"
    width="{{ asset.getWidth(imageTransform) / 2 }}"
  />
{% endif %}
{% endspaceless %}

Called as an include here:

{% include "_partials/_image" with {
   asset: image,
   classes: 'sidescroll__gallery__item__media',
   imageTransform: 'sideScrollImage'
   } only %}

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.