409

我正在访问我网站上的一个链接,每次访问该链接时都会提供一个新图像。

我遇到的问题是,如果我尝试在后台加载图像然后更新页面上的图像,图像不会改变——尽管当我重新加载页面时它会更新。

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

我需要强制刷新页面上的那个图像。有任何想法吗?

4

23 回答 23

410

尝试在 url 的末尾添加一个 cachebreaker:

newImage.src = "http://localhost/image.jpg?" + new Date().getTime();

这将在您创建图像时自动附加当前时间戳,并且它将使浏览器再次查找图像而不是检索缓存中的图像。

于 2009-07-02T22:46:10.430 回答
268

我已经看到如何做到这一点的答案有很多变化,所以我想我会在这里总结它们(加上我自己发明的第四种方法):


(1) 在 URL 中添加唯一的 cache-busting 查询参数,例如:

newImage.src = "image.jpg?t=" + new Date().getTime();

优点: 100% 可靠、快速且易于理解和实施。

缺点:完全绕过缓存,这意味着只要图像在视图之间没有变化,就会出现不必要的延迟和带宽使用。可能会用许多完全相同的图像的副本填充浏览器缓存(和任何中间缓存)!此外,需要修改图像 URL。

何时使用:当图像不断变化时使用,例如实时网络摄像头源。如果您使用此方法,请确保使用Cache-control: no-cacheHTTP 标头提供图像本身!!! (通常可以使用 .htaccess 文件进行设置)。否则,您将逐渐用旧版本的图像填充缓存!


(2) 将查询参数添加到仅在文件更改时才更改的 URL,例如:

echo '<img src="image.jpg?m=' . filemtime('image.jpg') . '">';

(这是 PHP 服务器端代码,但这里重要的一点是 ?m= [file last-modified time]查询字符串附加到文件名)。

优点: 100% 可靠、快速且易于理解和实施,并且完美地保留了缓存优势。

缺点:需要修改图像 URL。此外,服务器还需要做更多的工作——它必须访问文件最后修改时间。此外,需要服务器端信息,因此不适合纯客户端解决方案来检查刷新的图像。

何时使用:当您想缓存图像,但可能需要不时在服务器端更新它们而不更改文件名本身。并且当您可以轻松确保将正确的查询字符串添加到 HTML 中的每个图像实例时。


(3) 使用 header 提供图片Cache-control: max-age=0, must-revalidate,并在 URL 中添加唯一的memcache -busting 片段标识符,例如:

newImage.src = "image.jpg#" + new Date().getTime();

这里的想法是缓存控制标头将图像放入浏览器缓存中,但会立即将它们标记为陈旧,因此每次重新显示它们时,浏览器都必须与服务器检查它们是否已更改。这可确保浏览器的HTTP 缓存始终返回图像的最新副本。但是,浏览器通常会重复使用内存中的图像副本(如果有的话),甚至不会检查其 HTTP 缓存。为了防止这种情况,使用了片段标识符:内存中图像src的比较包含片段标识符,但在查询 HTTP 缓存之前它被剥离。(因此,例如image.jpg#Aimage.jpg#B可能都从image.jpg浏览器的 HTTP 缓存中的条目中显示,但是image.jpg#B永远不会使用image.jpg#A上次显示时内存中保留的图像数据显示)。

优点:正确使用 HTTP 缓存机制,如果缓存图像没有更改,则使用它们。适用于在添加到静态图像 URL 的查询字符串上阻塞的服务器(因为服务器永远不会看到片段标识符 - 它们仅供浏览器自己使用)。

缺点:依赖于浏览器的一些可疑(或至少记录不充分)的行为,关于在其 URL 中具有片段标识符的图像(但是,我已经在 FF27、Chrome33 和 IE11 中成功地测试了这一点)。仍然会为每个图像视图向服务器发送重新验证请求,如果图像很少更改和/或延迟是一个大问题,这可能是过度的(因为即使缓存的图像仍然很好,您也需要等待重新验证响应) . 需要修改图像 URL。

何时使用:当图像可能经常更改,或者需要由客户端间歇性刷新而无需服务器端脚本参与,但您仍希望缓存的优势时使用。例如,轮询实时网络摄像头,每隔几分钟不定期地更新图像。或者,如果您的服务器不允许在静态图像 URL 上使用查询字符串,则使用代替 (1) 或 (2)。

[编辑 2021:不再适用于最近的 Chrome 和 Edge:这些浏览器中的内部内存缓存现在忽略片段标识符(可能是因为切换到 Blink 引擎?)。但是请参阅下面的方法(4),现在在这两个浏览器上更容易,因此考虑将此方法与(4)的简化版本结合起来以涵盖这两个浏览器]。


(4) 使用 Javascript 强制刷新特定图像,首先将其加载到隐藏<iframe>然后调用location.reload(true)iframe 的contentWindow.

步骤是:

  • 将要刷新的图像加载到隐藏的 iframe 中。 [编辑 2021:对于 Chrome 和 Edge,加载带有<img>标签的 HTML 页面,而不是原始图像文件]。这只是一个设置步骤 - 如果需要,它可以在实际刷新之前很久完成。即使在这个阶段无法加载图像也没有关系!

  • [EDIT 2021:这一步现在在最近的 Chrome 和 Edge 中是不必要的]。完成后,将页面上或任何 DOM 节点中的任何位置(甚至是存储在 javascript 变量中的页外节点)上的该图像的所有副本都清空。这是必要的,因为浏览器可能会显示来自陈旧内存副本的图像(IE11 尤其如此):您需要确保在刷新 HTTP 缓存之前清除所有内存副本。如果其他 javascript 代码正在异步运行,您可能还需要同时阻止该代码创建要刷新的图像的新副本。

  • 打电话iframe.contentWindow.location.reload(true)true强制绕过缓存,直接从服务器重新加载并覆盖现有的缓存副本。

  • [编辑 2021:在最近的 Chrome 和 Edge 中,现在不需要此步骤 - 在这些浏览器上,现有图像将在上一步之后自动更新!]重新加载完成后,恢复空白图像。他们现在应该显示来自服务器的新版本!

对于同域图片,可以直接将图片加载到 iframe 中。 [编辑 2021:不在 Chrome、Edge 上]。对于跨域图像,您必须改为从您的域中加载包含<img>标签中图像的 HTML 页面,否则在尝试调用iframe.contentWindow.reload(...). [也为 Chrome 和 Edge 执行此操作]。

优点:就像你希望DOM 拥有的 image.reload() 函数一样工作!允许正常缓存图像(即使您需要它们,也可以使用未来的到期日期,从而避免频繁的重新验证)。允许您刷新特定图像,而无需更改当前页面或任何其他页面上该图像的 URL,仅使用客户端代码。

缺点:依赖于 Javascript。不能 100% 保证在每个浏览器中都能正常工作(尽管我已经在 FF27、Chrome33 和 IE11 中成功测试过)。相对于其他方法非常复杂。[编辑 2021:除非您只需要最近的 Chrome 和 Edge 支持,否则它会简单得多]。

何时使用:当您拥有一组想要缓存的基本静态图像时,您仍然需要能够偶尔更新它们并获得更新发生的即时视觉反馈。(尤其是当仅刷新整个浏览器页面不起作用时,例如在某些基于 AJAX 构建的 Web 应用程序中)。当方法 (1)-(3) 不可行时,因为(无论出于何种原因)您无法更改所有可能显示您需要更新的图像的 URL。(请注意,使用这 3 种方法会刷新图像,但如果另一个页面随后尝试在没有适当的查询字符串或片段标识符的情况下显示该图像,则它可能会显示旧版本)。

下面给出了以童话般的健壮和灵活的方式实现这一点的细节:

假设您的网站在 URL 路径中包含一个空白的 1x1 像素 .gif /img/1x1blank.gif,并且还具有以下一行 PHP 脚本(仅在对跨域图像应用强制刷新时需要,并且可以用任何服务器端脚本语言重写,当然)在 URL 路径/echoimg.php

<img src="<?=htmlspecialchars(@$_GET['src'],ENT_COMPAT|ENT_HTML5,'UTF-8')?>">

然后,这是您如何在 Javascript 中完成所有这些操作的实际实现。它看起来有点复杂,但是有很多注释,重要的函数只是 forceImgReload() - 前两个只是空白和非空白图像,应该设计为与您自己的 HTML 一起有效地工作,所以将它们编码为最适合您;您的网站可能不需要其中的许多复杂性:

// 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);
}

然后,要强制刷新与您的页面位于同一域的图像,您可以执行以下操作:

forceImgReload("myimage.jpg");

从其他地方(跨域)刷新图像:

forceImgReload("http://someother.server.com/someimage.jpg", true);

更高级的应用程序可能是在将新版本上传到服务器后重新加载图像,在上传的同时准备重新加载过程的初始阶段,以最大限度地减少用户可见的重新加载延迟。如果您通过 AJAX 进行上传,并且服务器返回一个非常简单的 JSON 数组 [success, width, height] 那么您的代码可能如下所示:

// 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));
}

最后一点:虽然这个主题是关于图像的,但它也可能适用于其他类型的文件或资源。例如,防止使用过时的脚本或 css 文件,或者甚至可能刷新更新的 PDF 文档(仅在设置为在浏览器中打开时使用 (4))。在这些情况下,方法 (4) 可能需要对上述 javascript 进行一些更改。

于 2014-03-15T21:12:20.327 回答
205

作为...的替代品

newImage.src = "http://localhost/image.jpg?" + new Date().getTime();

...看起来...

newImage.src = "http://localhost/image.jpg#" + new Date().getTime();

...足以在不绕过任何上游缓存的情况下欺骗浏览器缓存,假设您返回了正确的Cache-Control标头。虽然你可以使用...

Cache-Control: no-cache, must-revalidate

...你失去了If-Modified-SinceorIf-None-Match标头的好处,所以像...

Cache-Control: max-age=0, must-revalidate

...如果它实际上没有改变,应该阻止浏览器重新下载整个图像。在 IE、Firefox 和 Chrome 上测试并运行。令人讨厌的是它在 Safari 上失败,除非你使用...

Cache-Control: no-store

...尽管这仍然比用数百个相同的图像填充上游缓存更可取,特别是当它们在您自己的服务器上运行时。;-)

更新(2014-09-28):现在看来Cache-Control: no-storeChrome 也需要它。

于 2012-03-30T12:55:53.743 回答
9

创建新图像后,您是否要从 DOM 中删除旧图像并用新图像替换它?

您可能会在每次 updateImage 调用时获取新图像,但不会将它们添加到页面中。

有很多方法可以做到这一点。像这样的东西会起作用。

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);
}

在开始工作后,如果仍然存在问题,则可能是其他答案所讨论的缓存问题。

于 2009-07-02T23:44:12.013 回答
7
<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 秒内重新加载。我在带有不同类型家庭安全摄像头的页面上使用它。

于 2017-10-16T16:29:59.210 回答
5

您可以简单地使用fetch并设置缓存选项'reload'来更新缓存:

fetch("my-image-url.jpg", {cache: 'reload', mode: 'no-cors'})

以下函数将更新缓存并在页面中的任何位置重新加载图像:

const reloadImg = url =>
  fetch(url, { cache: 'reload', mode: 'no-cors' })
  .then(() => document.body.querySelectorAll(`img[src='${url}']`)
              .forEach(img => img.src = url))

它返回一个承诺,因此您可以根据需要使用它await reloadImg("my-image-url.jpg")

如今,fetch API几乎在任何地方都可用(当然,IE 除外)。

于 2021-02-22T08:20:20.290 回答
4

一个答案是像建议的那样随意添加一些获取查询参数。

更好的答案是在您的 HTTP 标头中发出几个额外的选项。

Pragma: no-cache
Expires: Fri, 30 Oct 1998 14:19:41 GMT
Cache-Control: no-cache, must-revalidate

通过提供过去的日期,它不会被浏览器缓存。Cache-Control在 HTTP/1.1 中添加了 must-revalidate 标记,表明即使在情有可原的情况下,代理也不应该提供旧图像,这Pragma: no-cache对于当前的现代浏览器/缓存并不是真正必要的,但可能有助于一些糟糕的破旧实现。

于 2009-07-02T22:57:03.230 回答
4

我有一个要求:1)不能?var=xx在图像中添加任何东西 2)它应该跨域工作

我真的很喜欢这个答案中的#4选项,但是:

  • 它在可靠地使用跨域时存在问题(并且需要接触服务器代码)。

我快速而肮脏的方式是:

  1. 创建隐藏的 iframe
  2. 将当前页面加载到它(是的整个页面)
  3. iframe.contentWindow.location.reload(true);
  4. 将图像源重新设置为自身

这里是

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);
}

是的,我知道,setTimeout ...您必须将其更改为正确的 onload-events。

于 2017-05-13T15:53:12.290 回答
3

我最终做的是让服务器将对该目录中图像的任何请求映射到我试图更新的源。然后我让计时器在名称的末尾附加一个数字,以便 DOM 将其视为新图像并加载它。

例如

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);
}
于 2009-08-17T15:18:27.100 回答
2

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')" />

于 2015-05-01T15:09:39.280 回答
2
document.getElementById("img-id").src = document.getElementById("img-id").src

将自己的 src 设置为它的 src。

于 2017-03-23T09:57:26.593 回答
2

该答案基于上述几个答案,但将它们统一和简化了一点,并将答案转换为 JavaScript 函数。

function refreshCachedImage(img_id) {
    var img = document.getElementById(img_id);
    img.src = img.src; // trick browser into reload
};

我需要一个解决方案来解决动画 SVG 在第一次播放后没有重新启动的问题。

这个技巧也适用于其他媒体,如音频和视频。

于 2021-05-12T21:40:59.410 回答
1

尝试使用无价值的查询字符串使其成为唯一的 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);
}
于 2009-07-02T22:46:44.140 回答
1

很大程度上基于 Doin 的 #4 代码,下面的示例大大简化了代码,document.write而不是src 在iframe支持 CORS 中。也只专注于破坏浏览器缓存,而不是重新加载页面上的每个图像。

下面是用$qtypescript promise 库编写并使用的,仅供参考,但应该很容易移植到 vanilla javascript。方法意味着存在于打字稿类中。angular

返回一个在 iframe 完成重新加载后将被解决的承诺。没有经过大量测试,但对我们来说效果很好。

    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;
    }
于 2016-10-13T22:39:39.360 回答
1

我改进了AlexMA的脚本,用于在网页上显示我的网络摄像头,该网页会定期上传具有相同名称的新图像。我遇到的问题是,有时由于图像损坏或未完整(上传)加载的图像而导致图像闪烁。为了防止闪烁,我检查了图像的自然高度,因为我的网络摄像头图像的大小没有改变。仅当加载的图像高度符合原始图像高度时,完整图像才会显示在页面上。

  <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>
于 2020-06-04T08:39:51.537 回答
1

将图像的第二个副本放在同一位置,然后删除原始图像。

function refreshImg(ele){
    ele.insertAdjacentHTML('beforebegin',ele.outerHTML);
    ele.parentNode.removeChild(ele);
}

这将有效地刷新图像。

跨浏览器也是。 insertAdjacentHTMLouterHTMLparentNoderemoveChild都是跨浏览器

在性能方面,在大多数情况下,性能损失很可能可以忽略不计。 @Paolo Bergantino 的回答可能比这个功能更好。使用他的答案只会影响一个 DOM 元素。具有此功能的两个元素。

于 2020-12-17T22:43:29.257 回答
1

我在使用 Unsplash 随机图像功能时遇到了同样的问题。在 URL 末尾添加一个虚拟查询字符串的想法是正确的,但在这种情况下,完全随机的参数不起作用(我试过了)。我可以想象它对于其他一些服务也是一样的,但是对于 unsplash,参数需要是sig,所以你的图像 URL 将是,例如,http://example.net/image.jpg?sig=RANDOM其中 random 是一个随机字符串,当你更新它时不会相同。我用过Math.random()*100,但日期也合适。

您需要执行上述操作,因为没有它,浏览器将看到所述路径处的图像已经加载,并将使用该缓存图像来加速加载。

https://github.com/unsplash/unsplash-source-js/issues/9

于 2021-02-20T23:33:20.453 回答
0

我通过 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());

然后从页面中,您只需为其提供带有一些参数的 servlet 即可获取正确的图像文件。

<img src="YourServlet?imageFileName=imageNum1">
于 2013-06-07T15:15:52.813 回答
0

这是我的解决方案。这很简单。帧调度可能会更好。

<!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>
于 2016-07-18T13:33:14.750 回答
0

以下代码可用于在单击按钮时刷新图像。

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')" />
于 2018-03-19T18:16:35.580 回答
0

不需要new Date().getTime()恶作剧。您可以通过使用不可见的虚拟图像并使用 jQuery .load() 来欺骗浏览器,然后每次都创建一个新图像:

<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>
于 2019-10-07T20:10:11.457 回答
0

简单的解决方案:将此标头添加到响应中:

Cache-control: no-store

这个权威页面清楚地解释了为什么这样做:https ://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control

它还解释了为什么no-cache不起作用。

其他答案不起作用,因为:

Caching.delete是关于您可以为离线工作创建的新缓存,请参阅:https ://web.dev/cache-api-quick-guide/

在 URL 中使用 # 的片段不起作用,因为 # 告诉浏览器不要向服务器发送请求。

将随机部分添加到 url 的缓存破坏器有效,但也会填充浏览器缓存。在我的应用程序中,我想每隔几秒从网络摄像头下载一张 5 MB 的图片。完全冻结您的电脑只需一个小时或更短的时间。我仍然不知道为什么浏览器缓存不限于合理的最大值,但这绝对是一个缺点。

于 2020-04-28T19:59:23.593 回答
-3

我使用了以下概念,首先将图像与错误(缓冲区)url 绑定,然后将其与有效 url 绑定。

imgcover.ImageUrl = ConfigurationManager.AppSettings["profileLargeImgPath"] + "Myapp_CoverPic_" + userid + "Buffer.jpg";

imgcover.ImageUrl = ConfigurationManager.AppSettings["profileLargeImgPath"] + "Myapp_CoverPic_" + userid + ".jpg";

这样,我强制浏览器使用有效的 url 刷新。

于 2017-07-28T10:17:19.227 回答