Automatic
The manual method if implementing Image Optimization is great if only a few images need to added to your website or content. However, it becomes very cumbersome when you want to instrument your whole website which may have hundreds or thousands of images.
In order to automatically optimize all of your images, it's best integrate using some custom code. The specific steps and code will differ depending on the platform being used, but some common examples are provided below.
Evolve Storefront
Evolve Storefront is already pre-integrated with Image Optimization. Simply configure the IMAGE_REQUEST_TEMPLATE
environment variable to your Image Optimization URL.
IMAGE_REQUEST_TEMPLATE=https://images-example.evolvestorefront.com/${src}?format=auto&width=${width}&height=${height}
Next.js
Next.js already includes an Image
component that optimizes images for you. It also has support to leverage an external image loader such as Evolve Image Optimization.
import Image from 'next/image'
const imageLoader = ({ src, width, height, quality }) => {
return `https://images-example.evolvestorefront.com/${src}?format=auto&width=${width}&height=${height}&quality=${quality || 75}`
}
export default function Page() {
return (
<Image
loader={imageLoader}
src="marketing/home_hero.jpg"
alt="Home Page Hero Image"
width={1024}
height={768}
/>
)
}
To automatically configure the imageLoader
for all of your images across your application, see loaderFile
configuration.
Generic JavaScript
To implement Evolve Image Optimization on any website, regardless of platform, JavaScript can be used to automatically update img
tags.
function optimizeImage(imgElement) {
// configure Image Optimization domain
const imageServerUrl = 'https://images-example.evolvestorefront.com';
const originalSrc = imgElement.getAttribute('src');
const width = imgElement.getAttribute('width') || '';
const height = imgElement.getAttribute('height') || '';
// build new URL and set src attribute
const optimizedSrc = `${imageServerUrl}/${encodeURIComponent(originalSrc)}?format=auto&width=${width}&height=${height}`;
imgElement.setAttribute('src', optimizedSrc);
return imgElement;
}
document.addEventListener('DOMContentLoaded', function() {
// find all images and optimize
const images = document.querySelectorAll('img');
images.forEach(img => {
optimizeImage(img);
});
});
The sample code above assumes:
- All of your image tags currently have a relative
src
attribute. For example,src="marketing/home_hero.jpg"
- If this is not the case, modify the
optimizeImage
function as needed.
- If this is not the case, modify the
- All images should be optimized
- To enable only specific images to be updated, modify the
DOMContentLoaded
listener function as needed. - For example, you can update the query selector to
img.io
and addclass="io"
to anyimg
tags you want optimized.
- To enable only specific images to be updated, modify the