Poll images through javascript

I need to poll the image using javascript and you need to perform an action as soon as the image is found in its position. This is the code I wrote 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 = 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----*/ 

The problem is that after one GET request, the response becomes cached and the request is not sent every time I install src. If you are viewing the NET tab, it only sends a request to the first src set and caches the response.

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

+4
source share
2 answers

Request an image using a different query string each time. The browser will treat it as a unique URL and will not have it in the cache. You can probably get away from this because the web server will probably ignore anything in the query string when requesting an image. The following should make 100 queries:

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

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 line will skip caching every time, as far as the browser is concerned, the image will be different (or potentially possible) each time you request the image, and there is no limit on the number of times you ask, since I hope the time will not stop ...

+4
source

Source: https://habr.com/ru/post/1332737/


All Articles