Reputation: 1601
I came across a very peculiar problem lately...
I've got the following HTML and javascript
<img id="mycoverpicture" src="users/<?php echo $_SESSION['username'] ?>/cover/cover.jpg" alt="">
I'm using dropzone to upload a JPEG image
$(".cover-picture").dropzone({
acceptedFiles: "image/jpeg",
url: 'includes/coveruploader.php',
maxFiles: 1,
maxfilesexceeded: function(file) {
this.removeAllFiles();
this.addFile(file);
},
success: function(file, response){
$('#mycoverpicture').attr('src','users/'+sessionuser+'/cover/cover.jpg');
}
});
As you can see, as the dropzone finishes uploading the cover picture, the image source changes. But the problem here is I have the following scenario.
Directory:
users/username/cover/cover.jpeg
When a user uploads a cover picture the cover.jpg is replaced there. So when the source of the image is changed dynamically, the old image still exists.
Is it because of the cache?
Should I clear the cache memory via PHP or JavaScript?
If I clear the cache memory, there is a problem again. When the user reloads the page or navigates to another page, all images and fonts would be downloaded again. Performance issue will exist...
I need a neat way to achieve the image change with same file name.
Upvotes: 0
Views: 565
Reputation: 37059
Try appending some random garbage to the image path, prefixed with a question mark. When you want to force the image to refresh, change the random garbage.
var filename = 'cover.jpg?r=' + Math.random().toString();
$('#mycoverpicture').attr('src','users/'+sessionuser+'/cover/'+filename);
This will defeat caching. The browser has no idea what the server is doing with that "query string" and will have to assume that it might be getting a new image, so it'll discard what's in cache. The server knows better and will simply ignore it the query string, and serve what it's currently got in that file -- the new image.
Upvotes: 2
Reputation: 25537
How about replace the existing image with a new one? That should remove the cache problem.
success: function (file, response) {
$("#mycoverpicture").replaceWith($("<img/>", {
src: 'users/' + sessionuser + '/cover/cover.jpg',
id: mycoverpicture
}));
}
Upvotes: 2