Creé un pequeño script que carga imágenes webp en lugar de jpg.
Sin embargo, puedo ver en la pestaña Red que la imagen se carga dos veces: versión jpg y versión webp.
image1.jpgun
image1.jpg?format=webp&quality=80¿Qué estoy haciendo mal?
Mi código:
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}')`; } }); }) Se usa en el archivo general.ts compilado en general.js
import { nativeNonLazyImage } from './nonLazyLoadWebpImages'; nativeNonLazyImage();Utilidades:
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; }Y estoy llamando a general.js después de que el cuerpo se represente:
<script src='~/js/general.js'></script>Cuando trato de llamarlo en el encabezado, no funciona, por ejemplo. la conversación no ocurre porque supongo que las imágenes aún no están cargadas.