Skip to content

New Feature: Use HTMLImageElement.decode() to pre-decode images #467

Open
@andrew-itscript

Description

@andrew-itscript

The decode is a newly added method that you can apply it to an Image object. This method will load, and then decode the image. Both are done in parallel, and does not affect the execution on the main thread. This obviously makes the page to render faster.

The return value of decode is a Promise. When the image decoding is finished successfully, this Promise will be resolved. In case of any image loading error, or decoding error the Promise will fail.

This method supported by most modern browsers and considered in Lazy-loading best practices. For more details you can check https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/decode

The changes are simple enough to add support of it in vue-lazyload:

const loadImageAsync = (item, resolve, reject) => {
  let image = new Image()
  if (!item || !item.src) {
    const err = new Error('image src is required')
    return reject(err)
  }

  image.src = item.src

  if ('decode' in image) {
    image.decode().then(function() {
      resolve({
        naturalHeight: image.naturalHeight,
        naturalWidth: image.naturalWidth,
        src: image.src
      })
    }).catch(function(e) {
      reject(e);
    });
  } else {
    image.onload = function() {
      resolve({
        naturalHeight: image.naturalHeight,
        naturalWidth: image.naturalWidth,
        src: image.src
      })
    }

    image.onerror = function(e) {
      reject(e)
    }
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions