Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: how to force Image() not to use the browser cache?

If I load the nextimg URL manually in the browser, it gives a new picture every time I reload. But this bit of code shows the same image every iteration of draw().

How can I force myimg not to be cached?

<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>
like image 261
Mark Harrison Avatar asked Oct 03 '08 00:10

Mark Harrison


2 Answers

You can't stop it from caching the image altogether within Javascript. But, you can toy with the src/address of the image to force it to cache anew:

[Image].src = 'image.png?' + (new Date()).getTime();

You can probably take any of the Ajax cache solutions and apply it here.

like image 155
Jonathan Lonowski Avatar answered Oct 20 '22 05:10

Jonathan Lonowski


The easiest way is to sling an ever-changing querystring onto the end:

var url = 'http://.../?' + escape(new Date())

Some people prefer using Math.random() for that instead of escape(new Date()). But the correct way is probably to alter the headers the web server sends to disallow caching.

like image 37
Dan Avatar answered Oct 20 '22 05:10

Dan