![](/img/trans.png)
[英]how to force ajax to use browser cache to not load the updated json file
[英]JavaScript: how to force Image() not to use the browser cache?
如果我在瀏覽器中手動加載nextimg URL,則每次重新加載時都會顯示新圖片。 但是這段代碼在draw()
每次迭代中顯示相同的圖像。
如何強制myimg不被緩存?
<html>
<head>
<script type="text/javascript">
function draw(){
var canvas = document.getElementById('canv');
var ctx = canvas.getContext('2d');
var rx;
var ry;
var i;
myimg = new Image();
myimg.src = 'http://ohm:8080/cgi-bin/nextimg'
rx=Math.floor(Math.random()*100)*10
ry=Math.floor(Math.random()*100)*10
ctx.drawImage(myimg,rx,ry);
window.setTimeout('draw()',0);
}
</script>
</head>
<body onload="draw();">
<canvas id="canv" width="1024" height="1024"></canvas>
</body>
</html>
最簡單的方法是將不斷變化的查詢字符串放到最后:
var url = 'http://.../?' + escape(new Date())
有些人更喜歡使用Math.random()
代替escape(new Date())
。 但正確的方法可能是更改Web服務器發送的標頭以禁止緩存。
你無法阻止它在Javascript中完全緩存圖像。 但是,您可以使用圖像的src /地址來強制它重新緩存:
[Image].src = 'image.png?' + (new Date()).getTime();
您可以使用任何Ajax緩存解決方案並在此處應用它。
這實際上聽起來像是瀏覽器中的一個錯誤 - 你可以在http://bugs.webkit.org上提交,如果它在Safari中,或者在https://bugzilla.mozilla.org/上用於Firefox。 為什么我說潛在的瀏覽器錯誤? 因為瀏覽器意識到它不應該在重新加載時緩存,但是當您以編程方式請求它時,它確實會為您提供圖像的緩存副本。
那說你確定你真的在畫任何東西嗎? Canvas.drawImage API不會等待加載圖像,並且當您嘗試使用圖像時,如果圖像尚未完全加載,則指定不繪制。
更好的做法是:
var myimg = new Image();
myimg.onload = function() {
var rx=Math.floor(Math.random()*100)*10
var ry=Math.floor(Math.random()*100)*10
ctx.drawImage(myimg,rx,ry);
window.setTimeout(draw,0);
}
myimg.src = 'http://ohm:8080/cgi-bin/nextimg'
(您也可以將draw
作為參數傳遞給setTimeout而不是使用字符串,這將保存重新分析並反復編譯相同的字符串。)
實際上,您需要繞過兩個緩存:一個是常規HTTP緩存,您可以通過在映像上使用正確的HTTP標頭來避免這些緩存。 但是你還必須阻止瀏覽器重新使用圖像的內存副本; 如果它決定它可以做到這一點,它甚至永遠不會到達查詢其緩存,所以HTTP標頭將無濟於事。
為防止這種情況,您可以使用更改的查詢字符串或更改的片段標識符。
請參見我的文章在這里了解更多詳情。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.