0

Android, Phonegap, jqm 1.4

When a user uploads a new profile pic in my app, it changes on the server, but since the img src is the same path (same path, new data), it doesn't update in the app (page refresh, building a new image element, etc.) I have to restart the app for the changes to take place.

Is there a way to refresh just the image elements so they will redownload the image?

I suppose it's cacheing the image... I'd like to keep cacheing in general, but just "un-cache" when a user changes their pic.

Note: This problem doesn't happen in my chrome/ripple emulator, it updates on page refresh.

Joe's Ideas
  • 492
  • 6
  • 22
  • Try replacing the img with its clone. `$('.profile').replaceWith($(.profile').clone());` or just replace `src` with same img src, this will refresh it. – Omar Dec 27 '13 at 20:46
  • @Omar Replacing the `src` exactly won't refresh the image; you need to change the path slightly. See my answer. – Trojan Dec 27 '13 at 21:25

3 Answers3

3

You need to change the image path to force it to be downloaded again. To do this, add an unused URL parameter to the end of the path, like this:

$("#myimg").attr("src", "/path/to/myimg.jpg?"+ new Date().getTime());
// OR
$("#myimg").attr("src", "/path/to/myimg.jpg?"+ Math.random());

Try it out for jQuery Mobile.

Trojan
  • 2,256
  • 28
  • 40
  • Great solution for the profile page. But I have a feed page that gets dynamically created (and refreshed each time you visit it), and if I use this method on them, they will be forced to always download, no cache... which slows it considerably. – Joe's Ideas Dec 28 '13 at 01:06
  • It seems refiring the app works the best: document.location.href = 'index.html'; – Joe's Ideas Dec 28 '13 at 01:11
  • @JoeLannen Interesting solution. Just curious, why do you need to reload if it's the same image? – Trojan Dec 28 '13 at 06:45
  • It's the same image path, but different image. – Joe's Ideas Dec 28 '13 at 07:27
2

The following small function reloads images by appending a hash to the source

(function($){
$.fn.ForceReload = function(UserSettings){

    // Settings
    var Settings = $.extend({
        Hash: new Date().getTime()
    }, UserSettings);

    // Image iteration
    this.each(function(){
        var _this = $(this);
        var img = _this.clone();
        var src = img.attr("src");
        img.attr("src", src + (src.indexOf("?") > -1 ? "&" : "?") + "hash=" + Settings.Hash).one("load", function(){    
            _this.after(img);
            _this.remove();
        });
    });
}
}(jQuery));

And use like:

$("img").ForceReload();
1

Reload Your Page:

$(document).ready(function() {
    setInterval(function(){
         location.reload();
     }, 1000);
});

Or:

$(document).ready(function() {
    setInterval(function(){
         $("#myimg").attr("src", "img.jpg?"+ new Date().getTime());
     }, 1000);
});
profimedica
  • 2,716
  • 31
  • 41