Hide Image When Anchor HREF Source Is Not Present - javascript

I would like to poll an anchor's href source about once every 5 seconds, to see whether a file at that address is present. When it is present, display an image in the anchor. In other words, the link is basically not there unless the file is present.
I'm guessing I would have to poll using an http HEAD request to determine whether the file exists, then toggle the image appropriately. Once the file has been determined to exist, I can stop polling and leave the image visible.
Is there a better way to do this, and can anyone suggest some script that would handle this functionality?

If your server is configured to do so you can use:
http://api.jquery.com/jQuery.ajax/
To poll for the file's existence by using the statusCode map
function checkFile() {
$.ajax({
statusCode: {
404: function() {
//file does not yet exist
setTimeout(checkFile, 5000);
}
200: function() {
//file exists.
showImage();
}
}
});
}
You may want to capture a few more edge cases though, (for example, an error callback).

// note, this piece of code assumes to be using jQuery
var interval = setInterval(function(){
var _el=$('#hrefId');
var href = _el.attr('href');
if(href == null || typeof href == 'undefined' || href == '')
return;
ajax call to href(in case on ur server(!) )
// on success
_el.attr('href','TheLink');
$('img', _el).show(); // show image
}, 5);

You can also use a socket library so the server can push a notification when the image is ready. socket.io seems like a good options here.
Another way would be to listen for the error event on the image, then wait for x milliseconds before trying to load it again. This is quite easy to implement, because every time you define a src attribute, the browser will add new listeners.
It’s basically the same as your meta-description but you don’t need to use ajax. You will also be able to load images from other domains (ajax have a cross-site policy):
var img = new Image(),
src = '/path/to/image.jpg';
img.onload = function() {
console.log('loaded', img);
};
img.onerror = function() {
window.setTimeout(function() {
img.src = src;
},500);
};
img.src = src;​
Here is a proof of concept: http://jsfiddle.net/L2L3U/. The program will try to load a 404 image for three seconds, after that I change the src to a real image and it will display it.

Related

How to detect if any of css/js files failed to load and alert user to refresh browser [duplicate]

I have an HTML page where several JavaScript, CSS and images files are referenced. These references are dynamically injected and user can manually copy the HTML page and the support files to another machine.
If some JS or CSS are missing, the browser complains in the console. For example:
Error GET file:///E:/SSC_Temp/html_005/temp/Support/jquery.js
I need somehow these errors reported back to me on the inline JavaScript of the HTML page so I can ask user to first verify that support files are copied correctly.
There's the window.onerror event which just inform me that there's a JS error on the page such as an Unexpected Syntax error, but this doesn't fire in the event of a 404 Not Found error. I want to check for this condition in case of any resource type, including CSS, JS, and images.
I do not like to use jQuery AJAX to verify that file physically exists - the I/O overhead is expensive for every page load.
The error report has to contain the name of the file missing so I can check if the file is core or optional.
Any Ideas?
To capture all error events on the page, you can use addEventListener with the useCapture argument set to true. The reason window.onerror will not do this is because it uses the bubble event phase, and the error events you want to capture do not bubble.
If you add the following script to your HTML before you load any external content, you should be able to capture all the error events, even when loading offline.
<script type="text/javascript">
window.addEventListener('error', function(e) {
console.log(e);
}, true);
</script>
You can access the element that caused the error through e.target. For example, if you want to know what file did not load on an img tag, you can use e.target.src to get the URL that failed to load.
NOTE: This technically will not detect the error code, it detects if the image failed to load, as it technically behaves the same regardless of the status code. Depending on your setup this would probably be enough, but for example if a 404 is returned with a valid image it will not trigger an error event.
you can use the onload and onerror attributes to detect the error
for example upon loading the following html it gives alert error1 and error2 you can call your own function e.g onerror(logError(this);) and record them in an Array and once the page is fully loaded post is with single Ajax call.
<html>
<head>
<script src="file:///SSC_Temp/html_005/temp/Support/jquery.js" onerror="alert('error1');" onload="alert('load');" type="text/javascript" ></script>
</head>
<body>
<script src="file:///SSC_Temp/html_005/temp/Support/jquery.js" onerror="alert('error2');" onload="alert('load');" type="text/javascript" ></script>
</body>
</html>
I've put together the code below in pure JavaScript, tested, and it works.
All the source code (html, css, and Javascript) + images and example font is here: on github.
The first code block is an object with methods for specific file extensions: html and css.
The second is explained below, but here is a short description.
It does the following:
the function check_file takes 2 arguments: a string path and a callback function.
gets the contents of given path
gets the file extension (ext) of the given path
calls the srcFrom [ext] object method that returns an array of relative paths that was referenced in the string context by src, href, etc.
makes a synchronous call to each of these paths in the paths array
halts on error, and returns the HTTP error message and the path that had a problem, so you can use it for other issues as well, like 403 (forbidden), etc.
For convenience, it resolves to relative path names and does not care about which protocol is used (http or https, either is fine).
It also cleans up the DOM after parsing the CSS.
var srcFrom = // object
{
html:function(str)
{
var prs = new DOMParser();
var obj = prs.parseFromString(str, 'text/html');
var rsl = [], nds;
['data', 'href', 'src'].forEach(function(atr)
{
nds = [].slice.call(obj.querySelectorAll('['+atr+']'));
nds.forEach(function(nde)
{ rsl[rsl.length] = nde.getAttribute(atr); });
});
return rsl;
},
css:function(str)
{
var css = document.createElement('style');
var rsl = [], nds, tmp;
css.id = 'cssTest';
css.innerHTML = str;
document.head.appendChild(css);
css = [].slice.call(document.styleSheets);
for (var idx in css)
{
if (css[idx].ownerNode.id == 'cssTest')
{
[].slice.call(css[idx].cssRules).forEach(function(ssn)
{
['src', 'backgroundImage'].forEach(function(pty)
{
if (ssn.style[pty].length > 0)
{
tmp = ssn.style[pty].slice(4, -1);
tmp = tmp.split(window.location.pathname).join('');
tmp = tmp.split(window.location.origin).join('');
tmp = ((tmp[0] == '/') ? tmp.substr(1) : tmp);
rsl[rsl.length] = tmp;
}
});
});
break;
}
}
css = document.getElementById('cssTest');
css.parentNode.removeChild(css);
return rsl;
}
};
And here is the function that gets the file contents and calls the above object method according to the file extension:
function check_file(url, cbf)
{
var xhr = new XMLHttpRequest();
var uri = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onload = function()
{
var ext = url.split('.').pop();
var lst = srcFrom[ext](this.response);
var rsl = [null, null], nds;
var Break = {};
try
{
lst.forEach(function(tgt)
{
uri.open('GET', tgt, false);
uri.send(null);
if (uri.statusText != 'OK')
{
rsl = [uri.statusText, tgt];
throw Break;
}
});
}
catch(e){}
cbf(rsl[0], rsl[1]);
};
xhr.send(null);
}
To use it, simply call it like this:
var uri = 'htm/stuff.html'; // html example
check_file(uri, function(err, pth)
{
if (err)
{ document.write('Aw Snap! "'+pth+'" is missing !'); }
});
Please feel free to comment and edit as you wish, i did this is a hurry, so it may not be so pretty :)
#alexander-omara gave the solution.
You can even add it in many files but the window handler can/should be added once.
I use the singleton pattern to achieve this:
some_global_object = {
error: (function(){
var activate = false;
return function(enable){
if(!activate){
activate = true;
window.addEventListener('error', function(e){
// maybe extra code here...
// if(e.target.custom_property)
// ...
}, true);
}
return activate;
};
}());
Now, from any context call it as many times you want as the handler is attached only once:
some_global_object.error();

image is not getting changed on ajax success [duplicate]

I am accessing a link on my site that will provide a new image each time it is accessed.
The issue I am running into is that if I try to load the image in the background and then update the one on the page, the image doesn't change--though it is updated when I reload the page.
var newImage = new Image();
newImage.src = "http://localhost/image.jpg";
function updateImage()
{
if(newImage.complete) {
document.getElementById("theText").src = newImage.src;
newImage = new Image();
number++;
newImage.src = "http://localhost/image/id/image.jpg?time=" + new Date();
}
setTimeout(updateImage, 1000);
}
Headers as FireFox sees them:
HTTP/1.x 200 OK
Cache-Control: no-cache, must-revalidate
Pragma: no-cache
Transfer-Encoding: chunked
Content-Type: image/jpeg
Expires: Fri, 30 Oct 1998 14:19:41 GMT
Server: Microsoft-HTTPAPI/1.0
Date: Thu, 02 Jul 2009 23:06:04 GMT
I need to force a refresh of just that image on the page. Any ideas?
Try adding a cachebreaker at the end of the url:
newImage.src = "http://localhost/image.jpg?" + new Date().getTime();
This will append the current timestamp automatically when you are creating the image, and it will make the browser look again for the image instead of retrieving the one in the cache.
I've seen a lot of variation in answers for how to do this, so I thought I'd summarize them here (plus add a 4th method of my own invention):
(1) Add a unique cache-busting query parameter to the URL, such as:
newImage.src = "image.jpg?t=" + new Date().getTime();
Pros: 100% reliable, quick & easy to understand and implement.
Cons: Bypasses caching altogether, meaning unnecessary delays and bandwidth use whenever the image doesn't change between views. Will potentially fill browser cache (and any intermediate caches) with many, many copies of exactly the same image! Also, requires modifying image URL.
When to use: Use when image is constantly changing, such as for a live webcam feed. If you use this method, make sure to serve the images themselves with Cache-control: no-cache HTTP headers!!! (Often this can be set up using a .htaccess file). Otherwise you'll be progressively filling caches up with old versions of the image!
(2) Add query parameter to the URL that changes only when the file does, e.g.:
echo '<img src="image.jpg?m=' . filemtime('image.jpg') . '">';
(That's PHP server-side code, but the important point here is just that a ?m=[file last-modified time] querystring is appended to the filename).
Pros: 100% reliable, quick & easy to understand and implement, and preserves caching advantages perfectly.
Cons: Requires modifying the image URL. Also, a little more work for the server - it has to get access to the file-last-modified time. Also, requires server-side information, so not suitable for a purely client-side-only solution to check for a refreshed image.
When to use: When you want to cache images, but may need to update them at the server end from time to time without changing the filename itself. AND when you can easily ensure that the correct querystring is added to every image instance in your HTML.
(3) Serve your images with the header Cache-control: max-age=0, must-revalidate, and add a unique memcache-busting fragment identifier to the URL, such as:
newImage.src = "image.jpg#" + new Date().getTime();
The idea here is that the cache-control header puts images in the browser cache, but immediately markes them stale, so that and every time they are re-displayed the browser must check with the server to see if they've changed. This ensures that the browser's HTTP cache always returns the latest copy of the image. However, browsers will often re-use an in-memory copy of an image if they have one, and not even check their HTTP cache in that case. To prevent this, a fragment identifier is used: Comparison of in-memory image src's includes the fragment identifier, but it gets stripped of before querying the HTTP cache. (So, e.g., image.jpg#A and image.jpg#B might both be displayed from the image.jpg entry in the browser's HTTP cache, but image.jpg#B would never be displayed using in-memory retained image data from when image.jpg#A was last displayed).
Pros: Makes proper use of HTTP caching mechanisms, and uses cached images if they haven't changed. Works for servers that choke on a querystring added to a static image URL (since servers never see fragment identifiers - they're for the browsers' own use only).
Cons: Relies on somewhat dubious (or at least poorly documented) behaviour of browsers, in regard to images with fragment identifiers in their URLs (However, I've tested this successfully in FF27, Chrome33, and IE11). Does still send a revalidation request to the server for every image view, which may be overkill if images only change rarely and/or latency is a big issue (since you need to wait for the revalidation response even when the cached image is still good). Requires modifying image URLs.
When to use: Use when images may change frequently, or need to be refreshed intermittently by the client without server-side script involvement, but where you still want the advantage of caching. For example, polling a live webcam that updates an image irregularly every few minutes. Alternatively, use instead of (1) or (2) if your server doesn't allow querystrings on static image URLs.
[EDIT 2021: No longer works on recent Chrome & Edge: The internal memcache in those browsers now ignores fragment identifiers (maybe since the switch to the Blink engine?). But see method (4) below, it's now MUCH easier on those two browsers specifically, so consider combining this method with a simplified version of (4) to cover those two browsers].
(4) Forcibly refresh a particular image using Javascript, by first loading it into a hidden <iframe> and then calling location.reload(true) on the iframe's contentWindow.
The steps are:
Load the image to be refreshed into a hidden iframe. [EDIT 2021: For Chrome and Edge, load a HTML page with an <img> tag, not the raw image file]. This is just a setup step - it can be done long in advance the actual refresh, if desired. It doesn't even matter if the image fails to load at this stage!
[EDIT 2021: This step is now unnecessary in recent Chrome and Edge]. Once that's done, blank out all copies of that image on your page(s) or anywhere in any DOM nodes (even off-page ones stored in javascript variables). This is necessary because the browser may otherwise display the image from a stale in-memory copy (IE11 especially does this): You need to ensure all in-memory copies are cleared, before refreshing the HTTP cache. If other javascript code is running asynchronously, you may also need to prevent that code from creating new copies of the to-be-refreshed image in the meantime.
Call iframe.contentWindow.location.reload(true). The true forces a cache bypass, reloading directly from the server and overwriting the existing cached copy.
[EDIT 2021: This step is now unnecessary in recent Chrome and Edge - on those browsers, existing images will just automatically update themselves after the previous step!] Once it's finished re-loading, restore the blanked images. They should now display the fresh version from the server!
For same-domain images, you can load the image into the iframe directly. [EDIT 2021: Not on Chrome, Edge]. For cross-domain images, you have to instead load a HTML page from your domain that contains the image in an <img> tag, otherwise you'll get an "Access Denied" error when trying to call iframe.contentWindow.reload(...). [Do this for Chrome & Edge also].
Pros: Works just like the image.reload() function you wish the DOM had! Allows images to by cached normally (even with in-the-future expiry dates if you want them, thus avoiding frequent revalidation). Allows you to refresh a particular image without altering the URLs for that image on the current page, or on any other pages, using only client-side code.
Cons: Relies on Javascript. Not 100% guaranteed to work properly in every browser (I've tested this successfully in FF27, Chrome33, and IE11 though). Very complicated relative to the other methods. [EDIT 2021: Unless you only need recent Chrome & Edge support, in which case it's very much simpler].
When to use: When you have a collection of basically static images that you'd like cached, but you still need to be able to update them occasionally and get immediate visual feedback that the update took place. (Especially when just refreshing the whole browser page wouldn't work, as in some web apps built on AJAX for example). And when methods (1)-(3) aren't feasible because (for whatever reason) you can't change all the URLs that might potentially display the image you need to have updated. (Note that using those 3 methods the image will be refreshed, but if another page then tries to displays that image without the appropriate querystring or fragment identifier, it may show an older version instead).
The details of implementing this in a fairy robust and flexible manner are given below:
Let's assume your website contains a blank 1x1 pixel .gif at the URL path /img/1x1blank.gif, and also has the following one-line PHP script (only required for applying forced refresh to cross-domain images, and can be rewritten in any server-side scripting language, of course) at the URL path /echoimg.php:
<img src="<?=htmlspecialchars(#$_GET['src'],ENT_COMPAT|ENT_HTML5,'UTF-8')?>">
Then, here's a realistic implementation of how you might do all this in Javascript. It looks a bit complicated, but there's a lot of comments, and the important function is just forceImgReload() - the first two just blank and un-blank images, and should be designed to work efficiently with your own HTML, so code them as works best for you; much of the complications in them may be unnecessary for your website:
// This function should blank all images that have a matching src, by changing their src property to /img/1x1blank.gif.
// ##### You should code the actual contents of this function according to your page design, and what images there are on them!!! #####
// Optionally it may return an array (or other collection or data structure) of those images affected.
// This can be used by imgReloadRestore() to restore them later, if that's an efficient way of doing it (otherwise, you don't need to return anything).
// NOTE that the src argument here is just passed on from forceImgReload(), and MAY be a relative URI;
// However, be aware that if you're reading the src property of an <img> DOM object, you'll always get back a fully-qualified URI,
// even if the src attribute was a relative one in the original HTML. So watch out if trying to compare the two!
// NOTE that if your page design makes it more efficient to obtain (say) an image id or list of ids (of identical images) *first*, and only then get the image src,
// you can pass this id or list data to forceImgReload() along with (or instead of) a src argument: just add an extra or replacement parameter for this information to
// this function, to imgReloadRestore(), to forceImgReload(), and to the anonymous function returned by forceImgReload() (and make it overwrite the earlier parameter variable from forceImgReload() if truthy), as appropriate.
function imgReloadBlank(src)
{
// ##### Everything here is provisional on the way the pages are designed, and what images they contain; what follows is for example purposes only!
// ##### For really simple pages containing just a single image that's always the one being refreshed, this function could be as simple as just the one line:
// ##### document.getElementById("myImage").src = "/img/1x1blank.gif";
var blankList = [],
fullSrc = /* Fully qualified (absolute) src - i.e. prepend protocol, server/domain, and path if not present in src */,
imgs, img, i;
for each (/* window accessible from this one, i.e. this window, and child frames/iframes, the parent window, anything opened via window.open(), and anything recursively reachable from there */)
{
// get list of matching images:
imgs = theWindow.document.body.getElementsByTagName("img");
for (i = imgs.length; i--;) if ((img = imgs[i]).src===fullSrc) // could instead use body.querySelectorAll(), to check both tag name and src attribute, which would probably be more efficient, where supported
{
img.src = "/img/1x1blank.gif"; // blank them
blankList.push(img); // optionally, save list of blanked images to make restoring easy later on
}
}
for each (/* img DOM node held only by javascript, for example in any image-caching script */) if (img.src===fullSrc)
{
img.src = "/img/1x1blank.gif"; // do the same as for on-page images!
blankList.push(img);
}
// ##### If necessary, do something here that tells all accessible windows not to create any *new* images with src===fullSrc, until further notice,
// ##### (or perhaps to create them initially blank instead and add them to blankList).
// ##### For example, you might have (say) a global object window.top.blankedSrces as a propery of your topmost window, initially set = {}. Then you could do:
// #####
// ##### var bs = window.top.blankedSrces;
// ##### if (bs.hasOwnProperty(src)) bs[src]++; else bs[src] = 1;
// #####
// ##### And before creating a new image using javascript, you'd first ensure that (blankedSrces.hasOwnProperty(src)) was false...
// ##### Note that incrementing a counter here rather than just setting a flag allows for the possibility that multiple forced-reloads of the same image are underway at once, or are overlapping.
return blankList; // optional - only if using blankList for restoring back the blanked images! This just gets passed in to imgReloadRestore(), it isn't used otherwise.
}
// This function restores all blanked images, that were blanked out by imgReloadBlank(src) for the matching src argument.
// ##### You should code the actual contents of this function according to your page design, and what images there are on them, as well as how/if images are dimensioned, etc!!! #####
function imgReloadRestore(src,blankList,imgDim,loadError);
{
// ##### Everything here is provisional on the way the pages are designed, and what images they contain; what follows is for example purposes only!
// ##### For really simple pages containing just a single image that's always the one being refreshed, this function could be as simple as just the one line:
// ##### document.getElementById("myImage").src = src;
// ##### if in imgReloadBlank() you did something to tell all accessible windows not to create any *new* images with src===fullSrc until further notice, retract that setting now!
// ##### For example, if you used the global object window.top.blankedSrces as described there, then you could do:
// #####
// ##### var bs = window.top.blankedSrces;
// ##### if (bs.hasOwnProperty(src)&&--bs[src]) return; else delete bs[src]; // return here means don't restore until ALL forced reloads complete.
var i, img, width = imgDim&&imgDim[0], height = imgDim&&imgDim[1];
if (width) width += "px";
if (height) height += "px";
if (loadError) {/* If you want, do something about an image that couldn't load, e.g: src = "/img/brokenImg.jpg"; or alert("Couldn't refresh image from server!"); */}
// If you saved & returned blankList in imgReloadBlank(), you can just use this to restore:
for (i = blankList.length; i--;)
{
(img = blankList[i]).src = src;
if (width) img.style.width = width;
if (height) img.style.height = height;
}
}
// Force an image to be reloaded from the server, bypassing/refreshing the cache.
// due to limitations of the browser API, this actually requires TWO load attempts - an initial load into a hidden iframe, and then a call to iframe.contentWindow.location.reload(true);
// If image is from a different domain (i.e. cross-domain restrictions are in effect, you must set isCrossDomain = true, or the script will crash!
// imgDim is a 2-element array containing the image x and y dimensions, or it may be omitted or null; it can be used to set a new image size at the same time the image is updated, if applicable.
// if "twostage" is true, the first load will occur immediately, and the return value will be a function
// that takes a boolean parameter (true to proceed with the 2nd load (including the blank-and-reload procedure), false to cancel) and an optional updated imgDim.
// This allows you to do the first load early... for example during an upload (to the server) of the image you want to (then) refresh.
function forceImgReload(src, isCrossDomain, imgDim, twostage)
{
var blankList, step = 0, // step: 0 - started initial load, 1 - wait before proceeding (twostage mode only), 2 - started forced reload, 3 - cancelled
iframe = window.document.createElement("iframe"), // Hidden iframe, in which to perform the load+reload.
loadCallback = function(e) // Callback function, called after iframe load+reload completes (or fails).
{ // Will be called TWICE unless twostage-mode process is cancelled. (Once after load, once after reload).
if (!step) // initial load just completed. Note that it doesn't actually matter if this load succeeded or not!
{
if (twostage) step = 1; // wait for twostage-mode proceed or cancel; don't do anything else just yet
else { step = 2; blankList = imgReloadBlank(src); iframe.contentWindow.location.reload(true); } // initiate forced-reload
}
else if (step===2) // forced re-load is done
{
imgReloadRestore(src,blankList,imgDim,(e||window.event).type==="error"); // last parameter checks whether loadCallback was called from the "load" or the "error" event.
if (iframe.parentNode) iframe.parentNode.removeChild(iframe);
}
}
iframe.style.display = "none";
window.parent.document.body.appendChild(iframe); // NOTE: if this is done AFTER setting src, Firefox MAY fail to fire the load event!
iframe.addEventListener("load",loadCallback,false);
iframe.addEventListener("error",loadCallback,false);
iframe.src = (isCrossDomain ? "/echoimg.php?src="+encodeURIComponent(src) : src); // If src is cross-domain, script will crash unless we embed the image in a same-domain html page (using server-side script)!!!
return (twostage
? function(proceed,dim)
{
if (!twostage) return;
twostage = false;
if (proceed)
{
imgDim = (dim||imgDim); // overwrite imgDim passed in to forceImgReload() - just in case you know the correct img dimensions now, but didn't when forceImgReload() was called.
if (step===1) { step = 2; blankList = imgReloadBlank(src); iframe.contentWindow.location.reload(true); }
}
else
{
step = 3;
if (iframe.contentWindow.stop) iframe.contentWindow.stop();
if (iframe.parentNode) iframe.parentNode.removeChild(iframe);
}
}
: null);
}
Then, to force a refresh of an image located on the same domain as your page, you can just do:
forceImgReload("myimage.jpg");
To refresh an image from somewhere else (cross-domain):
forceImgReload("http://someother.server.com/someimage.jpg", true);
A more advanced application might be to reload an image after uploading a new version to your server, preparing the initial stage of the reload process simultaneous with the upload, to minimize the visible reload delay to the user. If you're doing the upload via AJAX, and the server is returning a very simple JSON array [success, width, height] then your code might look something like this:
// fileForm is a reference to the form that has a the <input typ="file"> on it, for uploading.
// serverURL is the url at which the uploaded image will be accessible from, once uploaded.
// The response from uploadImageToServer.php is a JSON array [success, width, height]. (A boolean and two ints).
function uploadAndRefreshCache(fileForm, serverURL)
{
var xhr = new XMLHttpRequest(),
proceedWithImageRefresh = forceImgReload(serverURL, false, null, true);
xhr.addEventListener("load", function(){ var arr = JSON.parse(xhr.responseText); if (!(arr&&arr[0])) { proceedWithImageRefresh(false); doSomethingOnUploadFailure(...); } else { proceedWithImageRefresh(true,[arr[1],ar[2]]); doSomethingOnUploadSuccess(...); }});
xhr.addEventListener("error", function(){ proceedWithImageRefresh(false); doSomethingOnUploadError(...); });
xhr.addEventListener("abort", function(){ proceedWithImageRefresh(false); doSomethingOnUploadAborted(...); });
// add additional event listener(s) to track upload progress for graphical progress bar, etc...
xhr.open("post","uploadImageToServer.php");
xhr.send(new FormData(fileForm));
}
A final note: Although this topic is about images, it potentially applies to other kinds of files or resources also. For example, preventing the use of stale script or css files, or perhaps even refreshing updated PDF documents (using (4) only if set up to open in-browser). Method (4) might require some changes to the above javascript, in these cases.
As an alternative to...
newImage.src = "http://localhost/image.jpg?" + new Date().getTime();
...it seems that...
newImage.src = "http://localhost/image.jpg#" + new Date().getTime();
...is sufficient to fool the browser cache without bypassing any upstream caches, assuming you returned the correct Cache-Control headers. Although you can use...
Cache-Control: no-cache, must-revalidate
...you lose the benefits of the If-Modified-Since or If-None-Match headers, so something like...
Cache-Control: max-age=0, must-revalidate
...should prevent the browser from re-downloading the entire image if it hasn't actually changed. Tested and working on IE, Firefox, and Chrome. Annoyingly it fails on Safari unless you use...
Cache-Control: no-store
...although this still may be preferable to filling upstream caches with hundreds of identical images, particularly when they're running on your own server. ;-)
Update (2014-09-28): Nowadays it looks like Cache-Control: no-store is needed for Chrome as well.
2021 ANSWER: You can simply use fetch with the cache option set to 'reload' to update the cache:
fetch("my-image-url.jpg", {cache: 'reload', mode: 'no-cors'})
The following function will update the cache and reload your image everywhere in your page:
async function reloadImg(url) {
await fetch(url, { cache: 'reload', mode: 'no-cors' })
document.body.querySelectorAll(`img[src='${url}']`)
.forEach(img => img.src = url)
}
It returns a promise so you can use it like await reloadImg("my-image-url.jpg") if you wish.
Nowadays the fetch API is available almost everywhere (except on IE, of course).
After creating the new image, are you removing the old image from the DOM and replacing it with the new one?
You could be grabbing new images every updateImage call, but not adding them to the page.
There are a number of ways to do it. Something like this would work.
function updateImage()
{
var image = document.getElementById("theText");
if(image.complete) {
var new_image = new Image();
//set up the new image
new_image.id = "theText";
new_image.src = image.src;
// insert new image and remove old
image.parentNode.insertBefore(new_image,image);
image.parentNode.removeChild(image);
}
setTimeout(updateImage, 1000);
}
After getting that working, if there are still problems it is probably a caching issue like the other answers talk about.
<img src='someurl.com/someimage.ext' onload='imageRefresh(this, 1000);'>
Then below in some javascript
<script language='javascript'>
function imageRefresh(img, timeout) {
setTimeout(function() {
var d = new Date;
var http = img.src;
if (http.indexOf("&d=") != -1) { http = http.split("&d=")[0]; }
img.src = http + '&d=' + d.getTime();
}, timeout);
}
</script>
And so what this does is, when the image loads, schedules it to be reloaded in 1 second. I'm using this on a page with home security cameras of varying type.
I had a requirement: 1) can't add any ?var=xx to the image 2) it should work cross-domain
I really like the #4 option in this answer with one but:
it has problems working with crossdomain reliably (and it requires touching the server code).
My quick and dirty way is:
Create hidden iframe
Load the current page to it (yeah the whole page)
iframe.contentWindow.location.reload(true);
Re-set the image source to itself
Here it is
function RefreshCachedImage() {
if (window.self !== window.top) return; //prevent recursion
var $img = $("#MYIMAGE");
var src = $img.attr("src");
var iframe = document.createElement("iframe");
iframe.style.display = "none";
window.parent.document.body.appendChild(iframe);
iframe.src = window.location.href;
setTimeout(function () {
iframe.contentWindow.location.reload(true);
setTimeout(function () {
$img.removeAttr("src").attr("src", src);
}, 2000);
}, 2000);
}
Yeah, I know, setTimeout... You have to change that to proper onload-events.
One answer is to hackishly add some get query parameter like has been suggested.
A better answer is to emit a couple of extra options in your HTTP header.
Pragma: no-cache
Expires: Fri, 30 Oct 1998 14:19:41 GMT
Cache-Control: no-cache, must-revalidate
By providing a date in the past, it won't be cached by the browser. Cache-Control was added in HTTP/1.1 and the must-revalidate tag indicates that proxies should never serve up an old image even under extenuating circumstances, and the Pragma: no-cache isn't really necessary for current modern browsers/caches but may help with some crufty broken old implementations.
What I ended up doing was having the server map any request for an image at that directory to the source that I was trying to update. I then had my timer append a number onto the end of the name so the DOM would see it as a new image and load it.
E.g.
http://localhost/image.jpg
//and
http://localhost/image01.jpg
will request the same image generation code but it will look like different images to the browser.
var newImage = new Image();
newImage.src = "http://localhost/image.jpg";
var count = 0;
function updateImage()
{
if(newImage.complete) {
document.getElementById("theText").src = newImage.src;
newImage = new Image();
newImage.src = "http://localhost/image/id/image" + count++ + ".jpg";
}
setTimeout(updateImage, 1000);
}
function reloadImage(imageId)
{
path = '../showImage.php?cache='; //for example
imageObject = document.getElementById(imageId);
imageObject.src = path + (new Date()).getTime();
}
<img src='../showImage.php' id='myimage' />
<br/>
<input type='button' onclick="reloadImage('myimage')" />
This answer is based on several of the above answers but unifies and simplifies them a little and casts the answer as a JavaScript function.
function refreshCachedImage(img_id) {
var img = document.getElementById(img_id);
img.src = img.src; // trick browser into reload
};
I needed a solution to the problem of animated SVGs not restarting after they played through the first time.
This trick also works on other media like audio and video as well.
document.getElementById("img-id").src = document.getElementById("img-id").src
set its own src as its src.
I had this same issue using the Unsplash random image feature. The idea of adding a dummy query string to the end of the URL is correct, but in this instance a completely random parameter doesn't work (I tried it). I can imagine it's the same for some other services too, but for unsplash the parameter needs to be sig, so your image URL would be, for example, http://example.net/image.jpg?sig=RANDOM where random is a random string that will NOT be the same when you update it. I used Math.random()*100 but date is suitable too.
You need to do the above because without it, the browser will see that the image at said path has already been loaded, and will use that cached image to speed up loading.
See https://github.com/unsplash/unsplash-source-js/issues/9
Place a second copy of the image in the same spot, then remove the original image.
function refreshImg(ele){
ele.insertAdjacentHTML('beforebegin',ele.outerHTML);
ele.parentNode.removeChild(ele);
}
This will effectively refresh the image.
Crossbrowser too. insertAdjacentHTML, outerHTML, parentNode, and removeChild are all crossbrowser.
Performance wise, performance loss will most likely be negligible in most cases. #Paolo Bergantino's answer is probably better than this function. Only one DOM element is affected using his answer. Two elements with this function.
Try using a worthless querystring to make it a unique url:
function updateImage()
{
if(newImage.complete) {
document.getElementById("theText").src = newImage.src;
newImage = new Image();
number++;
newImage.src = "http://localhost/image.jpg?" + new Date();
}
setTimeout(updateImage, 1000);
}
Heavily based on Doin's #4 code, the below example simplifies that code a great bit utilising document.write instead of src in the iframe to support CORS. Also only focuses on busting the browser cache, not reloading every image on the page.
Below is written in typescript and uses the angular $q promise library, just fyi, but should be easy enough to port to vanilla javascript. Method is meant to live inside a typescript class.
Returns a promise that will be resolved when the iframe has completed reloading. Not heavily tested, but works well for us.
mmForceImgReload(src: string): ng.IPromise<void> {
var deferred = $q.defer<void>();
var iframe = window.document.createElement("iframe");
var firstLoad = true;
var loadCallback = (e) => {
if (firstLoad) {
firstLoad = false;
iframe.contentWindow.location.reload(true);
} else {
if (iframe.parentNode) iframe.parentNode.removeChild(iframe);
deferred.resolve();
}
}
iframe.style.display = "none";
window.parent.document.body.appendChild(iframe);
iframe.addEventListener("load", loadCallback, false);
iframe.addEventListener("error", loadCallback, false);
var doc = iframe.contentWindow.document;
doc.open();
doc.write('<html><head><title></title></head><body><img src="' + src + '"></body></html>');
doc.close();
return deferred.promise;
}
I improved the script from AlexMA for showing my webcam on a web page wich periodically uploads a new image with the same name. I had issues that sometimes the image was flickering because of a broken image or not complete (up)loaded image. To prevent flickering I check the natural height of the image because the size of my webcam image did not change. Only if the loaded image height fits the original image height the full image will be shown on page.
<h3>Webcam</h3>
<p align="center">
<img id="webcam" title="Webcam" onload="updateImage();" src="https://www.your-domain.com/webcam/current.jpg" alt="webcam image" width="900" border="0" />
<script type="text/javascript" language="JavaScript">
// off-screen image to preload next image
var newImage = new Image();
newImage.src = "https://www.your-domain.com/webcam/current.jpg";
// remember the image height to prevent showing broken images
var height = newImage.naturalHeight;
function updateImage()
{
// for sure if the first image was a broken image
if(newImage.naturalHeight > height)
{
height = newImage.naturalHeight;
}
// off-screen image loaded and the image was not broken
if(newImage.complete && newImage.naturalHeight == height)
{
// show the preloaded image on page
document.getElementById("webcam").src = newImage.src;
}
// preload next image with cachebreaker
newImage.src = "https://www.your-domain.com/webcam/current.jpg?time=" + new Date().getTime();
// refresh image (set the refresh interval to half of webcam refresh,
// in my case the webcam refreshes every 5 seconds)
setTimeout(updateImage, 2500);
}
</script>
</p>
I solved this problem by sending the data back through a servlet.
response.setContentType("image/png");
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache, must-revalidate");
response.setDateHeader("Expires", 0);
BufferedImage img = ImageIO.read(new File(imageFileName));
ImageIO.write(img, "png", response.getOutputStream());
Then from the page you just give it the servlet with some params to grab the correct image file.
<img src="YourServlet?imageFileName=imageNum1">
Here's my solution. It's very simple. The frame scheduling could be better.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Image Refresh</title>
</head>
<body>
<!-- Get the initial image. -->
<img id="frame" src="frame.jpg">
<script>
// Use an off-screen image to load the next frame.
var img = new Image();
// When it is loaded...
img.addEventListener("load", function() {
// Set the on-screen image to the same source. This should be instant because
// it is already loaded.
document.getElementById("frame").src = img.src;
// Schedule loading the next frame.
setTimeout(function() {
img.src = "frame.jpg?" + (new Date).getTime();
}, 1000/15); // 15 FPS (more or less)
})
// Start the loading process.
img.src = "frame.jpg?" + (new Date).getTime();
</script>
</body>
</html>
The following code is useful to refresh image when a button is clicked.
function reloadImage(imageId) {
imgName = 'vishnu.jpg'; //for example
imageObject = document.getElementById(imageId);
imageObject.src = imgName;
}
<img src='vishnu.jpg' id='myimage' />
<input type='button' onclick="reloadImage('myimage')" />
No need for new Date().getTime() shenanigans. You can trick the browser by having an invisible dummy image and using jQuery .load(), then creating a new image each time:
<img src="" id="dummy", style="display:none;" /> <!-- dummy img -->
<div id="pic"></div>
<script type="text/javascript">
var url = whatever;
// You can repeat the following as often as you like with the same url
$("#dummy").load(url);
var image = new Image();
image.src = url;
$("#pic").html("").append(image);
</script>
Simple solution: add this header to the response:
Cache-control: no-store
Why this works is clearly explained at this authoritative page: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control
It also explains why no-cache does not work.
Other answers do not work because:
Caching.delete is about a new cache that you may create for off-line work, see: https://web.dev/cache-api-quick-guide/
Fragments using a # in the URL do not work because the # tells the browser to not send a request to the server.
A cache-buster with a random part added to the url works, but will also fill the browser cache. In my app, I wanted to download a 5 MB picture every few seconds from a web cam. It will take just an hour or less to completely freeze your pc. I still don't know why the browser cache is not limited to a reasonable max, but this is definitely a disadvantage.
I used the below concept of first binding the image with a false(buffer) url and next binding it with the valid url.
imgcover.ImageUrl = ConfigurationManager.AppSettings["profileLargeImgPath"] + "Myapp_CoverPic_" + userid + "Buffer.jpg";
imgcover.ImageUrl = ConfigurationManager.AppSettings["profileLargeImgPath"] + "Myapp_CoverPic_" + userid + ".jpg";
This way, I am forcing the browser to refresh with valid url.

Asynchronously load images with jQuery

I want to load external images on my page asynchronously using jQuery and I have tried the following:
$.ajax({
url: "http://somedomain.com/image.jpg",
timeout:5000,
success: function() {
},
error: function(r,x) {
}
});
But it always returns error, is it even possible to load image like this?
I tried to use .load method and it works but I have no idea how I can set timeout if the image is not available (404). How can I do this?
No need for ajax. You can create a new image element, set its source attribute and place it somewhere in the document once it has finished loading:
var img = $("<img />").attr('src', 'http://somedomain.com/image.jpg')
.on('load', function() {
if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
alert('broken image!');
} else {
$("#something").append(img);
}
});
IF YOU REALLY NEED TO USE AJAX...
I came accross usecases where the onload handlers were not the right choice. In my case when printing via javascript. So there are actually two options to use AJAX style for this:
Solution 1
Use Base64 image data and a REST image service. If you have your own webservice, you can add a JSP/PHP REST script that offers images in Base64 encoding. Now how is that useful? I came across a cool new syntax for image encoding:
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhE..."/>
So you can load the Image Base64 data using Ajax and then on completion you build the Base64 data string to the image! Great fun :). I recommend to use this site http://www.freeformatter.com/base64-encoder.html for image encoding.
$.ajax({
url : 'BASE64_IMAGE_REST_URL',
processData : false,
}).always(function(b64data){
$("#IMAGE_ID").attr("src", "data:image/png;base64,"+b64data);
});
Solution2:
Trick the browser to use its cache. This gives you a nice fadeIn() when the resource is in the browsers cache:
var url = 'IMAGE_URL';
$.ajax({
url : url,
cache: true,
processData : false,
}).always(function(){
$("#IMAGE_ID").attr("src", url).fadeIn();
});
However, both methods have its drawbacks: The first one only works on modern browsers. The second one has performance glitches and relies on assumption how the cache will be used.
cheers,
will
Using jQuery you may simply change the "src" attribute to "data-src". The image won't be loaded. But the location is stored with the tag. Which I like.
<img class="loadlater" data-src="path/to/image.ext"/>
A Simple piece of jQuery copies data-src to src, which will start loading the image when you need it. In my case when the page has finished loading.
$(document).ready(function(){
$(".loadlater").each(function(index, element){
$(element).attr("src", $(element).attr("data-src"));
});
});
I bet the jQuery code could be abbreviated, but it is understandable this way.
$(<img />).attr('src','http://somedomain.com/image.jpg');
Should be better than ajax because if its a gallery and you are looping through a list of pics, if the image is already in cache, it wont send another request to server. It will request in the case of jQuery/ajax and return a HTTP 304 (Not modified) and then use original image from cache if its already there. The above method reduces an empty request to server after the first loop of images in the gallery.
You can use a Deferred objects for ASYNC loading.
function load_img_async(source) {
return $.Deferred (function (task) {
var image = new Image();
image.onload = function () {task.resolve(image);}
image.onerror = function () {task.reject();}
image.src=source;
}).promise();
}
$.when(load_img_async(IMAGE_URL)).done(function (image) {
$(#id).empty().append(image);
});
Please pay attention: image.onload must be before image.src to prevent problems with cache.
If you just want to set the source of the image you can use this.
$("img").attr('src','http://somedomain.com/image.jpg');
This works too ..
var image = new Image();
image.src = 'image url';
image.onload = function(e){
// functionalities on load
}
$("#img-container").append(image);
AFAIK you would have to do a .load() function here as apposed to the .ajax(), but you could use jQuery setTimeout to keep it live (ish)
<script>
$(document).ready(function() {
$.ajaxSetup({
cache: false
});
$("#placeholder").load("PATH TO IMAGE");
var refreshId = setInterval(function() {
$("#placeholder").load("PATH TO IMAGE");
}, 500);
});
</script>
use .load to load your image. to test if you get an error ( let's say 404 ) you can do the following:
$("#img_id").error(function(){
//$(this).hide();
//alert("img not loaded");
//some action you whant here
});
careful - .error() event will not trigger when the src attribute is empty for an image.
//Puedes optar por esta solución:
var img = document.createElement('img');
img.setAttribute('src', element.source)
img.addEventListener('load', function(){
if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
alert('broken image!');
} else {
$("#imagenesHub").append(img);
}
});
$(function () {
if ($('#hdnFromGLMS')[0].value == 'MB9262') {
$('.clr').append('<img src="~/Images/CDAB_london.jpg">');
}
else
{
$('.clr').css("display", "none");
$('#imgIreland').css("display", "block");
$('.clrIrland').append('<img src="~/Images/Ireland-v1.jpg">');
}
});

Post-loading : check if an image is in the browser cache

Short version question :
Is there navigator.mozIsLocallyAvailable equivalent function that works on all browsers, or an alternative?
Long version :)
Hi,
Here is my situation :
I want to implement an HtmlHelper extension for asp.net MVC that handle image post-loading easily (using jQuery).
So i render the page with empty image sources with the source specified in the "alt" attribute.
I insert image sources after the "window.onload" event, and it works great.
I did something like this :
$(window).bind('load', function() {
var plImages = $(".postLoad");
plImages.each(function() {
$(this).attr("src", $(this).attr("alt"));
});
});
The problem is : After the first loading, post-loaded images are cached. But if the page takes 10 seconds to load, the cached post-loaded images will be displayed after this 10 seconds.
So i think to specify image sources on the "document.ready" event if the image is cached to display them immediatly.
I found this function : navigator.mozIsLocallyAvailable to check if an image is in the cache. Here is what I've done with jquery :
//specify cached image sources on dom ready
$(document).ready(function() {
var plImages = $(".postLoad");
plImages.each(function() {
var source = $(this).attr("alt")
var disponible = navigator.mozIsLocallyAvailable(source, true);
if (disponible)
$(this).attr("src", source);
});
});
//specify uncached image sources after page loading
$(window).bind('load', function() {
var plImages = $(".postLoad");
plImages.each(function() {
if ($(this).attr("src") == "")
$(this).attr("src", $(this).attr("alt"));
});
});
It works on Mozilla's DOM but it doesn't works on any other one. I tried navigator.isLocallyAvailable : same result.
Is there any alternative?
after some reseach, I found a solution :
The idea is to log the cached images, binding a log function on the images 'load' event.
I first thought to store sources in a cookie, but it's not reliable if the cache is cleared without the cookie. Moreover, it adds one more cookie to HTTP requests...
Then i met the magic : window.localStorage (details)
The localStorage attribute provides
persistent storage areas for domains
Exactly what i wanted :). This attribute is standardized in HTML5, and it's already works on nearly all recent browsers (FF, Opera, Safari, IE8, Chrome).
Here is the code (without handling window.localStorage non-compatible browsers):
var storage = window.localStorage;
if (!storage.cachedElements) {
storage.cachedElements = "";
}
function logCache(source) {
if (storage.cachedElements.indexOf(source, 0) < 0) {
if (storage.cachedElements != "")
storage.cachedElements += ";";
storage.cachedElements += source;
}
}
function cached(source) {
return (storage.cachedElements.indexOf(source, 0) >= 0);
}
var plImages;
//On DOM Ready
$(document).ready(function() {
plImages = $(".postLoad");
//log cached images
plImages.bind('load', function() {
logCache($(this).attr("src"));
});
//display cached images
plImages.each(function() {
var source = $(this).attr("alt")
if (cached(source))
$(this).attr("src", source);
});
});
//After page loading
$(window).bind('load', function() {
//display uncached images
plImages.each(function() {
if ($(this).attr("src") == "")
$(this).attr("src", $(this).attr("alt"));
});
});
The most efficient, simple, and widely supported way to check if an image has already been cached is to do the following...
Create an image object
Set the src property to the desired url
Check the completed attribute immediately to see if the image is already cached
Set the src attribute back to "" (empty string), so that the image is not unnecessarily loaded (unless of coarse you want to load it at this time)
Like so...
function isCached(src) {
const img = new Image();
img.src = src;
const complete = img.complete;
img.src = "";
return complete;
}
In your case, it could be implemented like so...
const lazyImages = document.querySelectorAll(".postLoad");
for (const img of lazyImages) {
if ((!img.src || !isCached(img.src)) && img.getAttribute("alt")) {
img.src = img.getAttribute("alt");
}
}
That being said, I'd advise against using the alt attribute for this purpose, you should use something like data-src instead.
An ajax request for the image would return almost immediately if it is cached. Then use setTimeout to determine if its not ready and cancel the request so you can requeue it for later.
Update:
var lqueue = [];
$(function() {
var t,ac=0;
(t = $("img")).each(
function(i,e)
{
var rq = $.ajax(
{
cache: true,
type: "GET",
async:true,
url:e.alt,
success: function() { var rq3=rq; if (rq3.readyState==4) { e.src=e.alt; } },
error: function() { e.src=e.alt; }
});
setTimeout(function()
{
var k=i,e2=e,r2=rq;
if (r2.readyState != 4)
{
r2.abort();
lqueue.push(e2);
}
if (t.length==(++ac)) loadRequeue();
}, 0);
}
);
});
function loadRequeue()
{
for(var j = 0; j < lqueue.length; j++) lqueue[j].src=lqueue[j].alt;
}
I have a remark about your empty image sources. You wrote:
So i render the page with empty image sources with the source specified in the "alt" attribute. I insert image sources after the "window.onload" event, and it works great.
I've ran into problems with this in the past, because in some browsers empty src attributes cause extra requests. Here's what they do (copied from Yahoo! performance rules, there's also a blog post on that issue with more detail):
Internet Explorer makes a request to the directory in which the page is located.
Safari and Chrome make a request to the actual page itself.
Firefox 3 and earlier versions behave the same as Safari and Chrome, but version 3.5 addressed this issue[bug 444931] and no longer sends a request.
Opera does not do anything when an empty image src is encountered.
We also use a lot of jQuery on our site, and it has not always been possible to avoid empty image tags. I've chosen to use a 1x1 px transparent gif like so: src="t.gif" for images that I only insert after pageload. It is very small and gets cached by the browser. This has worked very well for us.
Cheers, Oliver
Just in case others may come across the same issue. some of the solutions provided here (namely storing the cache info in a local browser data storage) could break for two reasons. Firstly if cache of the image expires and secondly if the cache is cleared by the user. Another approach would be to set the source of image to an placeholder. Then changing the source to the image path/name. This way it becomes the responsibility of the browser to check its own cache. Should work with most browsers regardless of their API.
In 2017, Resource Timing API can help you check this using PerformanceResourceTiming.transferSize property. This property shall return non-zero transfer size when it is downloaded from server (not cached) and returns zero if fetched from a local cache.
Reference : https://developer.mozilla.org/en-US/docs/Web/API/PerformanceResourceTiming/transferSize
For anyone who might be trying to solve this problem with React I used the complete image property to solve it in React this way:
import React, { useState, useEffect, useRef } from 'react'
const Component= () => {
const [isLoadedImage, setLoadedImage] = useState(false)
const imageRef = useRef(null)
useEffect(() => {
const imgEl = imageRef.current
if (imgEl && imgEl.complete && !isLoadedImage) setLoadedImage(true)
})
return (
<img
onLoad={() => (!isLoadedImage ? setLoadedImage(true) : null)}
ref={imageRef}
/>
)
}

Refresh image with a new one at the same url

I am accessing a link on my site that will provide a new image each time it is accessed.
The issue I am running into is that if I try to load the image in the background and then update the one on the page, the image doesn't change--though it is updated when I reload the page.
var newImage = new Image();
newImage.src = "http://localhost/image.jpg";
function updateImage()
{
if(newImage.complete) {
document.getElementById("theText").src = newImage.src;
newImage = new Image();
number++;
newImage.src = "http://localhost/image/id/image.jpg?time=" + new Date();
}
setTimeout(updateImage, 1000);
}
Headers as FireFox sees them:
HTTP/1.x 200 OK
Cache-Control: no-cache, must-revalidate
Pragma: no-cache
Transfer-Encoding: chunked
Content-Type: image/jpeg
Expires: Fri, 30 Oct 1998 14:19:41 GMT
Server: Microsoft-HTTPAPI/1.0
Date: Thu, 02 Jul 2009 23:06:04 GMT
I need to force a refresh of just that image on the page. Any ideas?
Try adding a cachebreaker at the end of the url:
newImage.src = "http://localhost/image.jpg?" + new Date().getTime();
This will append the current timestamp automatically when you are creating the image, and it will make the browser look again for the image instead of retrieving the one in the cache.
I've seen a lot of variation in answers for how to do this, so I thought I'd summarize them here (plus add a 4th method of my own invention):
(1) Add a unique cache-busting query parameter to the URL, such as:
newImage.src = "image.jpg?t=" + new Date().getTime();
Pros: 100% reliable, quick & easy to understand and implement.
Cons: Bypasses caching altogether, meaning unnecessary delays and bandwidth use whenever the image doesn't change between views. Will potentially fill browser cache (and any intermediate caches) with many, many copies of exactly the same image! Also, requires modifying image URL.
When to use: Use when image is constantly changing, such as for a live webcam feed. If you use this method, make sure to serve the images themselves with Cache-control: no-cache HTTP headers!!! (Often this can be set up using a .htaccess file). Otherwise you'll be progressively filling caches up with old versions of the image!
(2) Add query parameter to the URL that changes only when the file does, e.g.:
echo '<img src="image.jpg?m=' . filemtime('image.jpg') . '">';
(That's PHP server-side code, but the important point here is just that a ?m=[file last-modified time] querystring is appended to the filename).
Pros: 100% reliable, quick & easy to understand and implement, and preserves caching advantages perfectly.
Cons: Requires modifying the image URL. Also, a little more work for the server - it has to get access to the file-last-modified time. Also, requires server-side information, so not suitable for a purely client-side-only solution to check for a refreshed image.
When to use: When you want to cache images, but may need to update them at the server end from time to time without changing the filename itself. AND when you can easily ensure that the correct querystring is added to every image instance in your HTML.
(3) Serve your images with the header Cache-control: max-age=0, must-revalidate, and add a unique memcache-busting fragment identifier to the URL, such as:
newImage.src = "image.jpg#" + new Date().getTime();
The idea here is that the cache-control header puts images in the browser cache, but immediately markes them stale, so that and every time they are re-displayed the browser must check with the server to see if they've changed. This ensures that the browser's HTTP cache always returns the latest copy of the image. However, browsers will often re-use an in-memory copy of an image if they have one, and not even check their HTTP cache in that case. To prevent this, a fragment identifier is used: Comparison of in-memory image src's includes the fragment identifier, but it gets stripped of before querying the HTTP cache. (So, e.g., image.jpg#A and image.jpg#B might both be displayed from the image.jpg entry in the browser's HTTP cache, but image.jpg#B would never be displayed using in-memory retained image data from when image.jpg#A was last displayed).
Pros: Makes proper use of HTTP caching mechanisms, and uses cached images if they haven't changed. Works for servers that choke on a querystring added to a static image URL (since servers never see fragment identifiers - they're for the browsers' own use only).
Cons: Relies on somewhat dubious (or at least poorly documented) behaviour of browsers, in regard to images with fragment identifiers in their URLs (However, I've tested this successfully in FF27, Chrome33, and IE11). Does still send a revalidation request to the server for every image view, which may be overkill if images only change rarely and/or latency is a big issue (since you need to wait for the revalidation response even when the cached image is still good). Requires modifying image URLs.
When to use: Use when images may change frequently, or need to be refreshed intermittently by the client without server-side script involvement, but where you still want the advantage of caching. For example, polling a live webcam that updates an image irregularly every few minutes. Alternatively, use instead of (1) or (2) if your server doesn't allow querystrings on static image URLs.
[EDIT 2021: No longer works on recent Chrome & Edge: The internal memcache in those browsers now ignores fragment identifiers (maybe since the switch to the Blink engine?). But see method (4) below, it's now MUCH easier on those two browsers specifically, so consider combining this method with a simplified version of (4) to cover those two browsers].
(4) Forcibly refresh a particular image using Javascript, by first loading it into a hidden <iframe> and then calling location.reload(true) on the iframe's contentWindow.
The steps are:
Load the image to be refreshed into a hidden iframe. [EDIT 2021: For Chrome and Edge, load a HTML page with an <img> tag, not the raw image file]. This is just a setup step - it can be done long in advance the actual refresh, if desired. It doesn't even matter if the image fails to load at this stage!
[EDIT 2021: This step is now unnecessary in recent Chrome and Edge]. Once that's done, blank out all copies of that image on your page(s) or anywhere in any DOM nodes (even off-page ones stored in javascript variables). This is necessary because the browser may otherwise display the image from a stale in-memory copy (IE11 especially does this): You need to ensure all in-memory copies are cleared, before refreshing the HTTP cache. If other javascript code is running asynchronously, you may also need to prevent that code from creating new copies of the to-be-refreshed image in the meantime.
Call iframe.contentWindow.location.reload(true). The true forces a cache bypass, reloading directly from the server and overwriting the existing cached copy.
[EDIT 2021: This step is now unnecessary in recent Chrome and Edge - on those browsers, existing images will just automatically update themselves after the previous step!] Once it's finished re-loading, restore the blanked images. They should now display the fresh version from the server!
For same-domain images, you can load the image into the iframe directly. [EDIT 2021: Not on Chrome, Edge]. For cross-domain images, you have to instead load a HTML page from your domain that contains the image in an <img> tag, otherwise you'll get an "Access Denied" error when trying to call iframe.contentWindow.reload(...). [Do this for Chrome & Edge also].
Pros: Works just like the image.reload() function you wish the DOM had! Allows images to by cached normally (even with in-the-future expiry dates if you want them, thus avoiding frequent revalidation). Allows you to refresh a particular image without altering the URLs for that image on the current page, or on any other pages, using only client-side code.
Cons: Relies on Javascript. Not 100% guaranteed to work properly in every browser (I've tested this successfully in FF27, Chrome33, and IE11 though). Very complicated relative to the other methods. [EDIT 2021: Unless you only need recent Chrome & Edge support, in which case it's very much simpler].
When to use: When you have a collection of basically static images that you'd like cached, but you still need to be able to update them occasionally and get immediate visual feedback that the update took place. (Especially when just refreshing the whole browser page wouldn't work, as in some web apps built on AJAX for example). And when methods (1)-(3) aren't feasible because (for whatever reason) you can't change all the URLs that might potentially display the image you need to have updated. (Note that using those 3 methods the image will be refreshed, but if another page then tries to displays that image without the appropriate querystring or fragment identifier, it may show an older version instead).
The details of implementing this in a fairy robust and flexible manner are given below:
Let's assume your website contains a blank 1x1 pixel .gif at the URL path /img/1x1blank.gif, and also has the following one-line PHP script (only required for applying forced refresh to cross-domain images, and can be rewritten in any server-side scripting language, of course) at the URL path /echoimg.php:
<img src="<?=htmlspecialchars(#$_GET['src'],ENT_COMPAT|ENT_HTML5,'UTF-8')?>">
Then, here's a realistic implementation of how you might do all this in Javascript. It looks a bit complicated, but there's a lot of comments, and the important function is just forceImgReload() - the first two just blank and un-blank images, and should be designed to work efficiently with your own HTML, so code them as works best for you; much of the complications in them may be unnecessary for your website:
// This function should blank all images that have a matching src, by changing their src property to /img/1x1blank.gif.
// ##### You should code the actual contents of this function according to your page design, and what images there are on them!!! #####
// Optionally it may return an array (or other collection or data structure) of those images affected.
// This can be used by imgReloadRestore() to restore them later, if that's an efficient way of doing it (otherwise, you don't need to return anything).
// NOTE that the src argument here is just passed on from forceImgReload(), and MAY be a relative URI;
// However, be aware that if you're reading the src property of an <img> DOM object, you'll always get back a fully-qualified URI,
// even if the src attribute was a relative one in the original HTML. So watch out if trying to compare the two!
// NOTE that if your page design makes it more efficient to obtain (say) an image id or list of ids (of identical images) *first*, and only then get the image src,
// you can pass this id or list data to forceImgReload() along with (or instead of) a src argument: just add an extra or replacement parameter for this information to
// this function, to imgReloadRestore(), to forceImgReload(), and to the anonymous function returned by forceImgReload() (and make it overwrite the earlier parameter variable from forceImgReload() if truthy), as appropriate.
function imgReloadBlank(src)
{
// ##### Everything here is provisional on the way the pages are designed, and what images they contain; what follows is for example purposes only!
// ##### For really simple pages containing just a single image that's always the one being refreshed, this function could be as simple as just the one line:
// ##### document.getElementById("myImage").src = "/img/1x1blank.gif";
var blankList = [],
fullSrc = /* Fully qualified (absolute) src - i.e. prepend protocol, server/domain, and path if not present in src */,
imgs, img, i;
for each (/* window accessible from this one, i.e. this window, and child frames/iframes, the parent window, anything opened via window.open(), and anything recursively reachable from there */)
{
// get list of matching images:
imgs = theWindow.document.body.getElementsByTagName("img");
for (i = imgs.length; i--;) if ((img = imgs[i]).src===fullSrc) // could instead use body.querySelectorAll(), to check both tag name and src attribute, which would probably be more efficient, where supported
{
img.src = "/img/1x1blank.gif"; // blank them
blankList.push(img); // optionally, save list of blanked images to make restoring easy later on
}
}
for each (/* img DOM node held only by javascript, for example in any image-caching script */) if (img.src===fullSrc)
{
img.src = "/img/1x1blank.gif"; // do the same as for on-page images!
blankList.push(img);
}
// ##### If necessary, do something here that tells all accessible windows not to create any *new* images with src===fullSrc, until further notice,
// ##### (or perhaps to create them initially blank instead and add them to blankList).
// ##### For example, you might have (say) a global object window.top.blankedSrces as a propery of your topmost window, initially set = {}. Then you could do:
// #####
// ##### var bs = window.top.blankedSrces;
// ##### if (bs.hasOwnProperty(src)) bs[src]++; else bs[src] = 1;
// #####
// ##### And before creating a new image using javascript, you'd first ensure that (blankedSrces.hasOwnProperty(src)) was false...
// ##### Note that incrementing a counter here rather than just setting a flag allows for the possibility that multiple forced-reloads of the same image are underway at once, or are overlapping.
return blankList; // optional - only if using blankList for restoring back the blanked images! This just gets passed in to imgReloadRestore(), it isn't used otherwise.
}
// This function restores all blanked images, that were blanked out by imgReloadBlank(src) for the matching src argument.
// ##### You should code the actual contents of this function according to your page design, and what images there are on them, as well as how/if images are dimensioned, etc!!! #####
function imgReloadRestore(src,blankList,imgDim,loadError);
{
// ##### Everything here is provisional on the way the pages are designed, and what images they contain; what follows is for example purposes only!
// ##### For really simple pages containing just a single image that's always the one being refreshed, this function could be as simple as just the one line:
// ##### document.getElementById("myImage").src = src;
// ##### if in imgReloadBlank() you did something to tell all accessible windows not to create any *new* images with src===fullSrc until further notice, retract that setting now!
// ##### For example, if you used the global object window.top.blankedSrces as described there, then you could do:
// #####
// ##### var bs = window.top.blankedSrces;
// ##### if (bs.hasOwnProperty(src)&&--bs[src]) return; else delete bs[src]; // return here means don't restore until ALL forced reloads complete.
var i, img, width = imgDim&&imgDim[0], height = imgDim&&imgDim[1];
if (width) width += "px";
if (height) height += "px";
if (loadError) {/* If you want, do something about an image that couldn't load, e.g: src = "/img/brokenImg.jpg"; or alert("Couldn't refresh image from server!"); */}
// If you saved & returned blankList in imgReloadBlank(), you can just use this to restore:
for (i = blankList.length; i--;)
{
(img = blankList[i]).src = src;
if (width) img.style.width = width;
if (height) img.style.height = height;
}
}
// Force an image to be reloaded from the server, bypassing/refreshing the cache.
// due to limitations of the browser API, this actually requires TWO load attempts - an initial load into a hidden iframe, and then a call to iframe.contentWindow.location.reload(true);
// If image is from a different domain (i.e. cross-domain restrictions are in effect, you must set isCrossDomain = true, or the script will crash!
// imgDim is a 2-element array containing the image x and y dimensions, or it may be omitted or null; it can be used to set a new image size at the same time the image is updated, if applicable.
// if "twostage" is true, the first load will occur immediately, and the return value will be a function
// that takes a boolean parameter (true to proceed with the 2nd load (including the blank-and-reload procedure), false to cancel) and an optional updated imgDim.
// This allows you to do the first load early... for example during an upload (to the server) of the image you want to (then) refresh.
function forceImgReload(src, isCrossDomain, imgDim, twostage)
{
var blankList, step = 0, // step: 0 - started initial load, 1 - wait before proceeding (twostage mode only), 2 - started forced reload, 3 - cancelled
iframe = window.document.createElement("iframe"), // Hidden iframe, in which to perform the load+reload.
loadCallback = function(e) // Callback function, called after iframe load+reload completes (or fails).
{ // Will be called TWICE unless twostage-mode process is cancelled. (Once after load, once after reload).
if (!step) // initial load just completed. Note that it doesn't actually matter if this load succeeded or not!
{
if (twostage) step = 1; // wait for twostage-mode proceed or cancel; don't do anything else just yet
else { step = 2; blankList = imgReloadBlank(src); iframe.contentWindow.location.reload(true); } // initiate forced-reload
}
else if (step===2) // forced re-load is done
{
imgReloadRestore(src,blankList,imgDim,(e||window.event).type==="error"); // last parameter checks whether loadCallback was called from the "load" or the "error" event.
if (iframe.parentNode) iframe.parentNode.removeChild(iframe);
}
}
iframe.style.display = "none";
window.parent.document.body.appendChild(iframe); // NOTE: if this is done AFTER setting src, Firefox MAY fail to fire the load event!
iframe.addEventListener("load",loadCallback,false);
iframe.addEventListener("error",loadCallback,false);
iframe.src = (isCrossDomain ? "/echoimg.php?src="+encodeURIComponent(src) : src); // If src is cross-domain, script will crash unless we embed the image in a same-domain html page (using server-side script)!!!
return (twostage
? function(proceed,dim)
{
if (!twostage) return;
twostage = false;
if (proceed)
{
imgDim = (dim||imgDim); // overwrite imgDim passed in to forceImgReload() - just in case you know the correct img dimensions now, but didn't when forceImgReload() was called.
if (step===1) { step = 2; blankList = imgReloadBlank(src); iframe.contentWindow.location.reload(true); }
}
else
{
step = 3;
if (iframe.contentWindow.stop) iframe.contentWindow.stop();
if (iframe.parentNode) iframe.parentNode.removeChild(iframe);
}
}
: null);
}
Then, to force a refresh of an image located on the same domain as your page, you can just do:
forceImgReload("myimage.jpg");
To refresh an image from somewhere else (cross-domain):
forceImgReload("http://someother.server.com/someimage.jpg", true);
A more advanced application might be to reload an image after uploading a new version to your server, preparing the initial stage of the reload process simultaneous with the upload, to minimize the visible reload delay to the user. If you're doing the upload via AJAX, and the server is returning a very simple JSON array [success, width, height] then your code might look something like this:
// fileForm is a reference to the form that has a the <input typ="file"> on it, for uploading.
// serverURL is the url at which the uploaded image will be accessible from, once uploaded.
// The response from uploadImageToServer.php is a JSON array [success, width, height]. (A boolean and two ints).
function uploadAndRefreshCache(fileForm, serverURL)
{
var xhr = new XMLHttpRequest(),
proceedWithImageRefresh = forceImgReload(serverURL, false, null, true);
xhr.addEventListener("load", function(){ var arr = JSON.parse(xhr.responseText); if (!(arr&&arr[0])) { proceedWithImageRefresh(false); doSomethingOnUploadFailure(...); } else { proceedWithImageRefresh(true,[arr[1],ar[2]]); doSomethingOnUploadSuccess(...); }});
xhr.addEventListener("error", function(){ proceedWithImageRefresh(false); doSomethingOnUploadError(...); });
xhr.addEventListener("abort", function(){ proceedWithImageRefresh(false); doSomethingOnUploadAborted(...); });
// add additional event listener(s) to track upload progress for graphical progress bar, etc...
xhr.open("post","uploadImageToServer.php");
xhr.send(new FormData(fileForm));
}
A final note: Although this topic is about images, it potentially applies to other kinds of files or resources also. For example, preventing the use of stale script or css files, or perhaps even refreshing updated PDF documents (using (4) only if set up to open in-browser). Method (4) might require some changes to the above javascript, in these cases.
As an alternative to...
newImage.src = "http://localhost/image.jpg?" + new Date().getTime();
...it seems that...
newImage.src = "http://localhost/image.jpg#" + new Date().getTime();
...is sufficient to fool the browser cache without bypassing any upstream caches, assuming you returned the correct Cache-Control headers. Although you can use...
Cache-Control: no-cache, must-revalidate
...you lose the benefits of the If-Modified-Since or If-None-Match headers, so something like...
Cache-Control: max-age=0, must-revalidate
...should prevent the browser from re-downloading the entire image if it hasn't actually changed. Tested and working on IE, Firefox, and Chrome. Annoyingly it fails on Safari unless you use...
Cache-Control: no-store
...although this still may be preferable to filling upstream caches with hundreds of identical images, particularly when they're running on your own server. ;-)
Update (2014-09-28): Nowadays it looks like Cache-Control: no-store is needed for Chrome as well.
2021 ANSWER: You can simply use fetch with the cache option set to 'reload' to update the cache:
fetch("my-image-url.jpg", {cache: 'reload', mode: 'no-cors'})
The following function will update the cache and reload your image everywhere in your page:
async function reloadImg(url) {
await fetch(url, { cache: 'reload', mode: 'no-cors' })
document.body.querySelectorAll(`img[src='${url}']`)
.forEach(img => img.src = url)
}
It returns a promise so you can use it like await reloadImg("my-image-url.jpg") if you wish.
Nowadays the fetch API is available almost everywhere (except on IE, of course).
After creating the new image, are you removing the old image from the DOM and replacing it with the new one?
You could be grabbing new images every updateImage call, but not adding them to the page.
There are a number of ways to do it. Something like this would work.
function updateImage()
{
var image = document.getElementById("theText");
if(image.complete) {
var new_image = new Image();
//set up the new image
new_image.id = "theText";
new_image.src = image.src;
// insert new image and remove old
image.parentNode.insertBefore(new_image,image);
image.parentNode.removeChild(image);
}
setTimeout(updateImage, 1000);
}
After getting that working, if there are still problems it is probably a caching issue like the other answers talk about.
<img src='someurl.com/someimage.ext' onload='imageRefresh(this, 1000);'>
Then below in some javascript
<script language='javascript'>
function imageRefresh(img, timeout) {
setTimeout(function() {
var d = new Date;
var http = img.src;
if (http.indexOf("&d=") != -1) { http = http.split("&d=")[0]; }
img.src = http + '&d=' + d.getTime();
}, timeout);
}
</script>
And so what this does is, when the image loads, schedules it to be reloaded in 1 second. I'm using this on a page with home security cameras of varying type.
I had a requirement: 1) can't add any ?var=xx to the image 2) it should work cross-domain
I really like the #4 option in this answer with one but:
it has problems working with crossdomain reliably (and it requires touching the server code).
My quick and dirty way is:
Create hidden iframe
Load the current page to it (yeah the whole page)
iframe.contentWindow.location.reload(true);
Re-set the image source to itself
Here it is
function RefreshCachedImage() {
if (window.self !== window.top) return; //prevent recursion
var $img = $("#MYIMAGE");
var src = $img.attr("src");
var iframe = document.createElement("iframe");
iframe.style.display = "none";
window.parent.document.body.appendChild(iframe);
iframe.src = window.location.href;
setTimeout(function () {
iframe.contentWindow.location.reload(true);
setTimeout(function () {
$img.removeAttr("src").attr("src", src);
}, 2000);
}, 2000);
}
Yeah, I know, setTimeout... You have to change that to proper onload-events.
One answer is to hackishly add some get query parameter like has been suggested.
A better answer is to emit a couple of extra options in your HTTP header.
Pragma: no-cache
Expires: Fri, 30 Oct 1998 14:19:41 GMT
Cache-Control: no-cache, must-revalidate
By providing a date in the past, it won't be cached by the browser. Cache-Control was added in HTTP/1.1 and the must-revalidate tag indicates that proxies should never serve up an old image even under extenuating circumstances, and the Pragma: no-cache isn't really necessary for current modern browsers/caches but may help with some crufty broken old implementations.
What I ended up doing was having the server map any request for an image at that directory to the source that I was trying to update. I then had my timer append a number onto the end of the name so the DOM would see it as a new image and load it.
E.g.
http://localhost/image.jpg
//and
http://localhost/image01.jpg
will request the same image generation code but it will look like different images to the browser.
var newImage = new Image();
newImage.src = "http://localhost/image.jpg";
var count = 0;
function updateImage()
{
if(newImage.complete) {
document.getElementById("theText").src = newImage.src;
newImage = new Image();
newImage.src = "http://localhost/image/id/image" + count++ + ".jpg";
}
setTimeout(updateImage, 1000);
}
function reloadImage(imageId)
{
path = '../showImage.php?cache='; //for example
imageObject = document.getElementById(imageId);
imageObject.src = path + (new Date()).getTime();
}
<img src='../showImage.php' id='myimage' />
<br/>
<input type='button' onclick="reloadImage('myimage')" />
This answer is based on several of the above answers but unifies and simplifies them a little and casts the answer as a JavaScript function.
function refreshCachedImage(img_id) {
var img = document.getElementById(img_id);
img.src = img.src; // trick browser into reload
};
I needed a solution to the problem of animated SVGs not restarting after they played through the first time.
This trick also works on other media like audio and video as well.
document.getElementById("img-id").src = document.getElementById("img-id").src
set its own src as its src.
I had this same issue using the Unsplash random image feature. The idea of adding a dummy query string to the end of the URL is correct, but in this instance a completely random parameter doesn't work (I tried it). I can imagine it's the same for some other services too, but for unsplash the parameter needs to be sig, so your image URL would be, for example, http://example.net/image.jpg?sig=RANDOM where random is a random string that will NOT be the same when you update it. I used Math.random()*100 but date is suitable too.
You need to do the above because without it, the browser will see that the image at said path has already been loaded, and will use that cached image to speed up loading.
See https://github.com/unsplash/unsplash-source-js/issues/9
Place a second copy of the image in the same spot, then remove the original image.
function refreshImg(ele){
ele.insertAdjacentHTML('beforebegin',ele.outerHTML);
ele.parentNode.removeChild(ele);
}
This will effectively refresh the image.
Crossbrowser too. insertAdjacentHTML, outerHTML, parentNode, and removeChild are all crossbrowser.
Performance wise, performance loss will most likely be negligible in most cases. #Paolo Bergantino's answer is probably better than this function. Only one DOM element is affected using his answer. Two elements with this function.
Try using a worthless querystring to make it a unique url:
function updateImage()
{
if(newImage.complete) {
document.getElementById("theText").src = newImage.src;
newImage = new Image();
number++;
newImage.src = "http://localhost/image.jpg?" + new Date();
}
setTimeout(updateImage, 1000);
}
Heavily based on Doin's #4 code, the below example simplifies that code a great bit utilising document.write instead of src in the iframe to support CORS. Also only focuses on busting the browser cache, not reloading every image on the page.
Below is written in typescript and uses the angular $q promise library, just fyi, but should be easy enough to port to vanilla javascript. Method is meant to live inside a typescript class.
Returns a promise that will be resolved when the iframe has completed reloading. Not heavily tested, but works well for us.
mmForceImgReload(src: string): ng.IPromise<void> {
var deferred = $q.defer<void>();
var iframe = window.document.createElement("iframe");
var firstLoad = true;
var loadCallback = (e) => {
if (firstLoad) {
firstLoad = false;
iframe.contentWindow.location.reload(true);
} else {
if (iframe.parentNode) iframe.parentNode.removeChild(iframe);
deferred.resolve();
}
}
iframe.style.display = "none";
window.parent.document.body.appendChild(iframe);
iframe.addEventListener("load", loadCallback, false);
iframe.addEventListener("error", loadCallback, false);
var doc = iframe.contentWindow.document;
doc.open();
doc.write('<html><head><title></title></head><body><img src="' + src + '"></body></html>');
doc.close();
return deferred.promise;
}
I improved the script from AlexMA for showing my webcam on a web page wich periodically uploads a new image with the same name. I had issues that sometimes the image was flickering because of a broken image or not complete (up)loaded image. To prevent flickering I check the natural height of the image because the size of my webcam image did not change. Only if the loaded image height fits the original image height the full image will be shown on page.
<h3>Webcam</h3>
<p align="center">
<img id="webcam" title="Webcam" onload="updateImage();" src="https://www.your-domain.com/webcam/current.jpg" alt="webcam image" width="900" border="0" />
<script type="text/javascript" language="JavaScript">
// off-screen image to preload next image
var newImage = new Image();
newImage.src = "https://www.your-domain.com/webcam/current.jpg";
// remember the image height to prevent showing broken images
var height = newImage.naturalHeight;
function updateImage()
{
// for sure if the first image was a broken image
if(newImage.naturalHeight > height)
{
height = newImage.naturalHeight;
}
// off-screen image loaded and the image was not broken
if(newImage.complete && newImage.naturalHeight == height)
{
// show the preloaded image on page
document.getElementById("webcam").src = newImage.src;
}
// preload next image with cachebreaker
newImage.src = "https://www.your-domain.com/webcam/current.jpg?time=" + new Date().getTime();
// refresh image (set the refresh interval to half of webcam refresh,
// in my case the webcam refreshes every 5 seconds)
setTimeout(updateImage, 2500);
}
</script>
</p>
I solved this problem by sending the data back through a servlet.
response.setContentType("image/png");
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache, must-revalidate");
response.setDateHeader("Expires", 0);
BufferedImage img = ImageIO.read(new File(imageFileName));
ImageIO.write(img, "png", response.getOutputStream());
Then from the page you just give it the servlet with some params to grab the correct image file.
<img src="YourServlet?imageFileName=imageNum1">
Here's my solution. It's very simple. The frame scheduling could be better.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Image Refresh</title>
</head>
<body>
<!-- Get the initial image. -->
<img id="frame" src="frame.jpg">
<script>
// Use an off-screen image to load the next frame.
var img = new Image();
// When it is loaded...
img.addEventListener("load", function() {
// Set the on-screen image to the same source. This should be instant because
// it is already loaded.
document.getElementById("frame").src = img.src;
// Schedule loading the next frame.
setTimeout(function() {
img.src = "frame.jpg?" + (new Date).getTime();
}, 1000/15); // 15 FPS (more or less)
})
// Start the loading process.
img.src = "frame.jpg?" + (new Date).getTime();
</script>
</body>
</html>
The following code is useful to refresh image when a button is clicked.
function reloadImage(imageId) {
imgName = 'vishnu.jpg'; //for example
imageObject = document.getElementById(imageId);
imageObject.src = imgName;
}
<img src='vishnu.jpg' id='myimage' />
<input type='button' onclick="reloadImage('myimage')" />
No need for new Date().getTime() shenanigans. You can trick the browser by having an invisible dummy image and using jQuery .load(), then creating a new image each time:
<img src="" id="dummy", style="display:none;" /> <!-- dummy img -->
<div id="pic"></div>
<script type="text/javascript">
var url = whatever;
// You can repeat the following as often as you like with the same url
$("#dummy").load(url);
var image = new Image();
image.src = url;
$("#pic").html("").append(image);
</script>
Simple solution: add this header to the response:
Cache-control: no-store
Why this works is clearly explained at this authoritative page: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control
It also explains why no-cache does not work.
Other answers do not work because:
Caching.delete is about a new cache that you may create for off-line work, see: https://web.dev/cache-api-quick-guide/
Fragments using a # in the URL do not work because the # tells the browser to not send a request to the server.
A cache-buster with a random part added to the url works, but will also fill the browser cache. In my app, I wanted to download a 5 MB picture every few seconds from a web cam. It will take just an hour or less to completely freeze your pc. I still don't know why the browser cache is not limited to a reasonable max, but this is definitely a disadvantage.
I used the below concept of first binding the image with a false(buffer) url and next binding it with the valid url.
imgcover.ImageUrl = ConfigurationManager.AppSettings["profileLargeImgPath"] + "Myapp_CoverPic_" + userid + "Buffer.jpg";
imgcover.ImageUrl = ConfigurationManager.AppSettings["profileLargeImgPath"] + "Myapp_CoverPic_" + userid + ".jpg";
This way, I am forcing the browser to refresh with valid url.

Categories