Skip to content
Advertisement

Append cachebreaker to filenames of all images of a type

I’m able to identify all images of type (SVG) and append a cachebreaking date string in the console log.

allImg = document.querySelectorAll('img[src$=".svg"');

imgTime = Date.now();

allImg.forEach(img => console.log(img.src + '#' + imgTime));

I’ve been looking at this solution, but it’s only for individual filenames, not multiple images: https://stackoverflow.com/a/1077051/3787666

Any help appreciated.

Advertisement

Answer

Okay, here’s how it works, adding a cachebreaker to every SVG image in a page:

allImg = document.querySelectorAll('img[src$=".svg"');

imgTime = Date.now();

allImg.forEach(img => {
    //console.log(img.src);
  newImgSrc = img.src + '?' + imgTime;
    //console.log(newImgSrc);
  img.src = newImgSrc;
});

Caveat is that this forces the SVGs to load a second time, so, if it’s feasible to write the cachebuster into the original IMG SRC, that would generally be preferable. The site constraints in this particular use case mean that’s not an option.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement