Home > Software design >  Append cachebreaker to filenames of all images of a type
Append cachebreaker to filenames of all images of a type

Time:12-08

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.

CodePudding user response:

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.

  • Related