Search code examples
javascriptcssimagedomlivereload

How can I trigger images reload regardless of where they're used (CSS background-image, pseudo-element, style attribute, img tag)


I'm trying to set up a livereload server that reloads image assets as they change on disk. No page refresh, just the media files, reloaded.

Trouble is these assets can appear in a lot of different forms:

  • <style> CSS background-image: url('http://localhost:8080/myasset.png');
  • <link> CSS background: url('http://localhost:8080/myasset.png') no-repeat 50%;
  • style attribute background-image
  • ::before/::after pseudo-element CSS
  • <img> source, srcset
  • <video> src, <source> srcs
  • etc.

<img> src updates are easy

var liveUrl = imgTag.getAttribute('src');
liveUrl = __addUrlQueryParam(liveUrl, '_lf', Date.now());
imgTag.setAttribute('src', liveUrl);

But to try to update the URL in this way for CSS style declarations, or pseudo-elements... sounds downright depressing.

Is there an alternative technique I could use to trigger asset reload universally over the entire page?

Only the URL string is known. The element where it's used is not. It would have to somehow search the DOM for the element, find the style declaration where the URL appears, and have the ability to set that style declaration to a URL with ?_lf=1493306569919 appended. Also, it may not be in the styleSheets because it's overridden in DevTools. So just window.getComputedStyles, but that's read-only. And .getMatchedCSSRules is deprecated and WebKit-only.


Solution

  • live-server seems to have the desired behavior.

    Running live-server --wait=100 --port=80 --host=livereload . reacts the same way as the demo in my other answer:

    Demo of live asset reloading feature: what works in my fork of gulp-server-livereload works in live-server too