我正在访问我的网站上的一个链接,每次访问它都会提供一个新的图像。
我遇到的问题是,如果我试图在后台加载图像,然后更新页面上的图像,图像不会改变——尽管在我重新加载页面时它会更新。
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);
}
FireFox看到的头文件:
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
我需要强制刷新页面上的图像。什么好主意吗?
<img src='someurl.com/someimage.ext' onload='imageRefresh(this, 1000);'>
然后在下面的一些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>
这个做的是,当图像加载时,安排它在1秒内重新加载。我在不同类型的家庭安全摄像头的页面上使用这个。
我最终要做的是让服务器将对该目录下的图像的任何请求映射到我试图更新的源。然后,我让计时器在名称的末尾附加一个数字,这样DOM就会将其视为新图像并加载它。
E.g.
http://localhost/image.jpg
//and
http://localhost/image01.jpg
将请求相同的图像生成代码,但它将看起来像不同的图像浏览器。
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 refreshImg(ele){
ele.insertAdjacentHTML('beforebegin',ele.outerHTML);
ele.parentNode.removeChild(ele);
}
这将有效地刷新图像。
Crossbrowser。insertAdjacentHTML, outerHTML, parentNode和removecchild都是跨浏览器的。
在大多数情况下,性能损失几乎可以忽略不计。@Paolo Bergantino的答案可能比这个函数更好。使用他的答案,只有一个DOM元素受到影响。这个函数有两个元素。
<img src='someurl.com/someimage.ext' onload='imageRefresh(this, 1000);'>
然后在下面的一些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>
这个做的是,当图像加载时,安排它在1秒内重新加载。我在不同类型的家庭安全摄像头的页面上使用这个。
简单的解决方案:在响应中添加以下报头:
Cache-control: no-store
为什么这样做是清楚地解释在这个权威的页面:https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control
这也解释了为什么无缓存不能工作。
其他答案并不适用,因为:
cache .delete是关于您可以为脱机工作创建的新缓存,请参阅:https://web.dev/cache-api-quick-guide/
在URL中使用#的片段不起作用,因为#告诉浏览器不要向服务器发送请求。
一个随机添加到url的缓存破坏者可以工作,但也会填满浏览器缓存。在我的应用程序中,我想每隔几秒钟从网络摄像头下载一张5mb的图片。完全冻结你的电脑只需要一个小时或更少的时间。我仍然不知道为什么浏览器缓存不限制在一个合理的最大值,但这绝对是一个缺点。