1

I have the code below that fetches images from a directory and displays in HTML. The images in this directory constantly change every second. It works somewhat on desktop browsers, but I cannot make it work on mobile browsers. It seems that it's always reading the cached images rather than reloading from the server. It can work by hitting ctrl+F5 on desktop browsers, but not on mobile browsers. Is there a way to hard refresh a mobile browser (chrome) via JavaScript?

<html>
<head>
<meta http-equiv="Cache-control" content="no-cache">
<meta http-equiv="Expires" content="-1">
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
 <img id="viewer" src="" width="100%"/>
 <div id="info"> </div>
 <button id="btnLeft" type="button">Left</button>
 <button id="btnRight" type="button">Right</button>
 <input type="button" value="Refresh page" onclick="location.reload(true);" />

<script>
$(function() {
 var baseUrl = "./Cam01/";
 var pictureIndex = 0;
 var pictures = [];
 function getFiles() {
  $.ajax(baseUrl).success(function(data) {
   pictures = [];
   $(data).find("a[href]").each(function() {
    var href = $(this).attr('href');
    if (href.indexOf('.jpg') > 0 || href.indexOf('.png') > 0 || href.indexOf('.jpeg') > 0) {
     pictures.push(href);
    }
   });
   console.log(pictures.length + " pictures loaded!");
   changePicture(0);
  });
 }
 function changePicture(indexOffset) {
  pictureIndex += indexOffset;
  if (pictureIndex >= pictures.length) {
   pictureIndex = 0;
  } else if (pictureIndex < 0) {
   pictureIndex = pictures.length - 1;
  }
  $('#viewer').attr('src', baseUrl + pictures[pictureIndex]);
  $('#info').text((pictureIndex + 1) + "/" + pictures.length);
 }

 getFiles();
 
 $('#btnLeft').click(function() {
 var left = -1;
    changePicture(left); return false;
 });
 $('#btnRight').click(function() {
 var right = 1;
    changePicture(right); return false;
 });
 
 $(document).keydown(function(e){
  var left = -1, right = 1;
     if (e.keyCode == 37) {
        changePicture(left); return false;
     } else if (e.keyCode == 39) {
      changePicture(right); return false;
     }
 });
 
});
</script>
</body>
</html>
TLS
  • 3,090
  • 2
  • 25
  • 33
JCprog
  • 85
  • 1
  • 10
  • Why would you want to force mobile users to continuously load more data? – Ajaypayne Mar 08 '18 at 18:07
  • In projects where images change regularly, I like to append the "file modified" timestamp to the URL. See [Cache busting via params](https://stackoverflow.com/questions/9692665/cache-busting-via-params#comment72170040_9692722). – showdev Mar 08 '18 at 18:10
  • @Ajaypayne, it's only a remote image viewer for personal project use. Data usage is not quite a concern. – JCprog Mar 08 '18 at 18:17
  • Okay, then to make sure that you always have the latest and not the cache, you should look at @showdev s comment – Ajaypayne Mar 08 '18 at 18:22
  • @showdev, I look into your link and I'm not exactly sure how to implement this. – JCprog Mar 08 '18 at 18:48
  • What language is the server-side code that your AJAX calls? – showdev Mar 08 '18 at 18:52
  • The script inside html only looks for images in a directory and displays them. no other method is called. But its an Apache server if that's what your asking. – JCprog Mar 08 '18 at 19:03
  • Oh, I see. You are parsing the directory index page? Does that page include accurate ["last modified"](https://webmasters.stackexchange.com/questions/48505/where-does-apache-get-the-last-modifed-date-for-its-automatic-indexes) times? – showdev Mar 08 '18 at 19:08
  • no it doesn't, depending on how many images is currently saved in that directory e.g. 100 images its would only treat the images as items e.g. 1 of 100. – JCprog Mar 08 '18 at 19:18
  • Possible duplicate of [Refresh image with a new one at the same url](https://stackoverflow.com/questions/1077041/refresh-image-with-a-new-one-at-the-same-url) – showdev Mar 08 '18 at 19:28

1 Answers1

0

One method to prevent loading an image from cache is to append a timestamp to its URL.
This causes the resource to seem "fresh" because it's different from the last time it was loaded.

I prefer using the "file modified" timestamp so that only images that have changed since the last load are refreshed. Images that haven't changed could be loaded from cache. But, it seems you're parsing a directory index page and that timestamp isn't available to you.

You can append the current timestamp to the URLs to prevent caching. But as @Ajaypayne alluded, this could cause unnecessarily high bandwidth use because it prevents caching even if an image hasn't changed.

Something like this:

var href = $(this).attr('href') + '?'+Date.now();

Edit

Actually, since images are loaded upon button press, I would add the timestamp inside the changePicture() function instead of on page load:

$('#viewer').attr('src', baseUrl + pictures[pictureIndex] + '?'+Date.now());

Edit

Incidentally, jQuery's .ajax() function accepts a cache parameter for GET requests:

cache (default: true, false for dataType 'script' and 'jsonp')
Type: Boolean
If set to false, it will force requested pages not to be cached by the browser. Note: Setting cache to false will only work correctly with HEAD and GET requests. It works by appending "_={timestamp}" to the GET parameters. The parameter is not needed for other types of requests, except in IE8 when a POST is made to a URL that has already been requested by a GET.

So maybe:

$.ajax({
  url: baseUrl,
  method: "GET",
  cache: false
}).done(function(data) {
  // process data here
});
showdev
  • 28,454
  • 37
  • 55
  • 73
  • This seem to work on cache-busting the images. As I am testing this repeatedly, It seems the major problem is the indexing of the images. lets say I have 5 images right now and a minute later I have 10, the indexing method doesn't updated to current. – JCprog Mar 08 '18 at 19:45
  • Hm, I see. Maybe the directory listing itself is cached? What happens if you append a timestamp to `baseUrl`? – showdev Mar 08 '18 at 19:47
  • You may also want to try jQuery's `cache` parameter for `.ajax()`. It uses a similar method of adding a timestamp. Please see edit. – showdev Mar 08 '18 at 20:05
  • I took a different route regarding caching the base document. I use .htaccess which works for updating the index, the downside is it affects all .html within my server. Is there a way to target specific directory only? – JCprog Mar 08 '18 at 20:48
  • I'd think you can just put that `.htaccess` file in the directory you want it to affect. – showdev Mar 08 '18 at 20:56
  • That pretty much solved my problem! Thanks a million showdev! – JCprog Mar 08 '18 at 21:01