React Storefront
|

Optimizing Images

Configuring the Image Optimization Service

By default Moovweb legacy image optimization service is used. You can override this by adding the following to src/App.js in your app:

// src/App.js

import { configureImageService, XDN_IMAGE_SERVICE } from 'react-storefront/imageService'

configureImageService(XDN_IMAGE_SERVICE)

Image Component

To display individual images as React components, use React Storefront's Image React component. You can downscale the image using the quality prop, with takes a number from 1 to 100 corresponding to the percent the image should be downscaled. You can also use the lazy to delay loading the image until it is visible in the viewport. Here's an example:

import Image from 'react-storefront/Image'

export default Component({ image }) {
  return <Image src={image} quality={80} lazy />
}

Images within CMS content

React Storefront provides the following functions to help optimize images found in HTML stored in your CMS:

optimizeImages(options)

Transform images using Moovweb's CDN with the following options:

  • quality A number or string containing the number for the desired quality, on a scale from 1 (worst) to 100 (best).
  • width A number or string containing the number for the desired pixel width.
  • height A number or string containing the number for the desired pixel height.
  • format A string containing the desired file format. Options include jpg, png, and webp.
  • sourceAttributes An array of the attributes which contain the image source.
  • preventLayoutInstability Wrap the image in a container which fills the aspect ratio of the original image.

lazyLoadImages()

Delays the loading of each image until it is visible in the viewport. You must set CmsSlot's lazyLoadImages prop in order to use this feature.

Example Usage

import parse from 'react-storefront-extensions/html/parse'

export default somePageHandler(params, request) {
  const html = await fetchUpstreamHtml()
  const $ = parse(html)
  $('img').optimizeImages({ quality: 80 })
  $('img').lazyLoadImages()
  return {
    content: $('.content').html()
  }
}

Tip: There are situations where alternative attributes are used for image sources, such as data-src. You can specify those attributes in the options of optimizeImages using the sourceAttributes prop.

$('img').optimizeImages({ width: 500, sourceAttributes: ['src', 'data-src'] })