问题
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