Jim's Depository

this code is not yet written
 

I have a web site which displays a remote camera view. I like to update the <img> once a minute or so without forcing a page reload and all of its flicker. I’ve done many horrible things over the years, mostly related to adding a query parameter to the end of the URL and accepting that I will trash the cache and perform redundant downloads when the image is not changing.

The <img> tag is 21 years old, surely if it can drink in the USA it has had a .refresh() method added. brief check of specifications: and no.

stackoverflow is littered with questions and solutions about how to reload an <img>, most of them involve cache busting serial numbers in the query parameters.

Notable exceptions:

  • Some answers recommend using a hash tag serial, since this should leave the URL to the server unchanged. This works in some browsers, but doesn’t cause a reload in others. Sometimes there is a combination of HTTP Cache-control headers that will cause a reload, sometimes not. Too touchy to use.

  • You can use an <iframe> containing just the URI of your image to force a reload using an actual, supported mechanism! When that completes you can bludgeon your <img> tag enough to use the new version. See Method #4. I have dispensed with replacing the <img> element and just set the src to null and back. This keeps Safari and Chrome from flickering in January of 2015.

The <iframe> method is my new favorite. It requires Javascript, but I’m not sure how you would be deciding to refresh without Javascript, so that isn’t a loss. From Safari, it does cause two requests for the resource, but the second will be a 304 if you are using any sane caching mechanisms, and the first will only be a 200 if it really changed. (We are in 2015 and I don’t worry so much about the extra request since the servers are all SPDY and its not like its a new TCP connection or blocking anything else.)

Note to W3C: Add .reload() method which tells an <img> to reconsider the caching information and make a new request if required. I suppose a force boolean argument wouldn’t be too much. But nothing more complicated.