Force refresh an image in jquery mobile

ぐ巨炮叔叔 提交于 2019-12-12 06:47:25

问题


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.


回答1:


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.




回答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();



回答3:


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);
});


来源:https://stackoverflow.com/questions/20807367/force-refresh-an-image-in-jquery-mobile

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!