我正在访问我的网站上的一个链接,每次访问它都会提供一个新的图像。
我遇到的问题是,如果我试图在后台加载图像,然后更新页面上的图像,图像不会改变——尽管在我重新加载页面时它会更新。
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
我需要强制刷新页面上的图像。什么好主意吗?
我最终要做的是让服务器将对该目录下的图像的任何请求映射到我试图更新的源。然后,我让计时器在名称的末尾附加一个数字,这样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);
}
我最终要做的是让服务器将对该目录下的图像的任何请求映射到我试图更新的源。然后,我让计时器在名称的末尾附加一个数字,这样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);
}
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.
您需要这样做,因为如果没有它,浏览器将看到所述路径上的图像已经加载,并将使用缓存的图像来加速加载。
参见https://github.com/unsplash/unsplash-source-js/issues/9