开发者

image polling through javascript

开发者 https://www.devze.com 2023-01-31 05:07 出处:网络
I need to poll an image using javascript and need to perform an action once the image is found at its position. This is the code I have written for this task.

I need to poll an image using javascript and need to perform an action once the image is found at its position. This is the code I have written for this task.

/*----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 = functio开发者_StackOverflow中文版n(){    
   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----*/

Problem is that, after one GET request, the response gets cached and request don't get sent everytime I set src. If you examine NET tab, it sends request only on first src set and caches the response.

I need to send a fresh request for image every time my code sets the src. Any workarounds?


Change your src to include the current EPOCH time as a variable.

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

Using a different variable in the query string each time will miss out caching, because as far as the browser is concerned, the image is different (or potentially could be) each time you request the image, and there is no limit to the amount of times you ask, as time hopefully will not stop...


Request the image with a different query string each time. The browser will treat it as a unique URL and won't have it in the cache. You can probably get away with this because it's likely the web server will ignore anything in the query string when requesting an image. The following should make 100 requests:

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

精彩评论

暂无评论...
验证码 换一张
取 消