I have created a small script that loads webp images instead of jpg.
However I can see in Network tab that the image is loaded twice - jpg version and webp version.
image1.jpg
an
image1.jpg?format=webp&quality=80
What am I doing wrong?
My code:
import { webpSrc } from '../shared/utils/utilities';
export const nativeNonLazyImage = (async () => {
// All imgs that does not use lozad lazy loading
const images = document.querySelectorAll("img:not(.lazy)");
images.forEach(function(img) {
if(img instanceof HTMLImageElement && img.src) {
img.src = webpSrc(img.src);
}
});
// All background images that does not use lozad lazy loading
const bgImages = document.querySelectorAll('*:not(.lazy)[style*="background-image"]');
bgImages.forEach(function(elem) {
const bgImage = window.getComputedStyle(elem).getPropertyValue('background-image');
if(bgImage) {
const imgUrl = bgImage.replace("url\(","").replace("\)","").replace("\"","").replace("\"","");
const newBgImage = webpSrc(imgUrl);
let element = elem as HTMLElement;
element.style.backgroundImage = `url('${newBgImage}')`;
}
});
})
Used in general.ts file compiled to general.js
import { nativeNonLazyImage } from './nonLazyLoadWebpImages';
nativeNonLazyImage();
Utilities:
import { isWebpSupported } from 'react-image-webp/dist/utils';
import { WEBP_FORMATS } from '../constants/constants';
const extensionFromUrl = (url: string) => {
if(url) {
const path = url.split('?')[0];
const urlParts = path.split('.');
return urlParts[urlParts.length-1];
}
return url;
};
export const webpSrc = (inputImgSrc: string) => {
const fileExtension = extensionFromUrl(inputImgSrc);
const urlSrcHasQueryString = inputImgSrc && inputImgSrc.includes("?");
if(isWebpSupported && WEBP_FORMATS.indexOf(fileExtension) >= 0)
return `${inputImgSrc}${(urlSrcHasQueryString ? `&` : `?`)}format=webp&quality=80`;
return inputImgSrc;
}
And I am calling general.js after the body rendered:
<script src='~/js/general.js'></script>
When I try to call it in the header it doesn't work, eg. the conversaion doesn't happen as I guess the images are not loaded yet.