2010-12-20 84 views
4

我需要使用JavaScript轮询图像,并且需要在图像位于其位置时执行操作。这是我为此任务编写的代码。通过javascript图像轮询

/*----Image handling script starts here----*/ 
var beacon = new Image(); 
beacon.onload = function() { 
    console.log('Image found'); 
    console.log(this.width,this.height); 
    window.clearInterval(timer); 
}; 
beacon.onerror = function(){  
    console.log('Image not found'); 
} 
var timer = window.setInterval(function(){ 
    console.log('sending the request again'); 
    beacon.src = "http://www.google.co.in/logos/2010/lennon10-hp.gif"; 
},2000); 
/*----Image handling script ends here----*/ 

问题是,一个GET请求后,响应被缓存,并要求不要让每次送我设置SRC。如果您检查NET选项卡,它仅在第一个src集中发送请求并缓存响应。

每当我的代码设置src时,我需要发送一个新的图像请求。任何解决方法?

回答

2

每次请求具有不同查询字符串的图像。浏览器将它视为一个唯一的URL,并不会将其放入缓存中。你可能会逃避这一点,因为在请求图像时,Web服务器可能会忽略查询字符串中的任何内容。以下应该提出100个请求:

for (var i=0; i<100; i++) 
{ 
    beacon.src = "http://www.google.co.in/logos/2010/lennon10-hp.gif?" + i; 
} 
4

更改您的src以包含当前EPOCH时间作为变量。

beacon.src = "http://www.google.co.in/logos/2010/lennon10-hp.gif?" + 
    date.getTime(); 

查询字符串,每次使用一个不同的变量会错过缓存,因为据浏览器而言,图像是不同的(或潜在的可能),每次请求的图像时,有是没有限制你问的次数,因为时间有希望不会停止...