0

I have an image that i upload via FTP to my host server, for now i`m using a function with a 10 seconds interval to add a random number to the image.src and reload the image, but this cost too much bandwidth, so i'm searching for a way to reload the element only when the file on the server has been modified.

Function with the interval:

setInterval(function reload() {
    var d = new Date();
    document.getElementById("imageOne").src="folder/image.png?a="+d.getTime();
}, 10000);
WillDFz
  • 19
  • 2
  • 1
    Use HTTP caching headers. – SLaks Jul 15 '18 at 02:34
  • Are you in control of the server? You could use SSE to notify the client that there's been an update. Otherwise, you're going to have to do polling which will take some bandwidth. – Brad Jul 15 '18 at 03:32

1 Answers1

0

There are some technologies that let you subscribe to a server. I don't know exactly how to do it and this question on a similar subject suggests there aren't allot of people who have a clear cut answer. Hopefully it does get a good answer.

If you can afford more server side processing: what I would do on the php side would be to: on request from javascript; keep open a connection as long as possible with some kind of wait loop checking if the file has updated. Putting this loop on the php side would reduce packet traffic and increase server load. Eventually before php times out you want to return an answer so the browser would know to reopen it's connection this can be as big as the entire file or as small as an empty packet (an empty packet is still 64 bytes).

If you can afford a packet or two I don't know how performant you need your application to be. Just checking for the last updated header will save you from downloading the file every time. This post to a question on getting a files' last modified time stamp will help you; if you don't know how to write ajax to do this.

If you can't decide, checking for the header has the least chance of going horribly wrong. I would go for that first and then try the other methods if it's still too expensive. A hybrid option would be my next suggestion if that isn't good enough.

haelmic
  • 541
  • 4
  • 18