Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

150
Visualizações
Images loaded twice - jpg and webp version after converting to webp and calling it after body renders

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.

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda