我们目前选择的解决方案:
- 我们计划为图像设置适当的标题(请参阅这个非常好的答案)
- 我们存储在渲染 URL 时使用的更新图像的本地列表
第 2 部分可能需要一些解释:幸运的是,我们在前端使用了一个非常好的 JS 框架,它允许我们定义任意方法并在模板中使用它们。我们的模型有一个返回照片 URL 的方法,这个 URL 用于每个模板。
上传新图片时,我们将 id 与 localStorage 中的当前时间戳关联:
window.localStorage['nocache.'+id] = new Date().getTime()
每当我们请求图像路径时,我们都会查看 localStorage 以查看是否必须将时间戳附加到 URL,否则 URL 会按原样返回。
优点/改进
- 用户自己触发的更新将立即可用,不仅在缓存过期后。
- 所有其他资源都使用缓存。
- 我们会查看
localStorage
我们正在构建的每个图像 URL。这可能很昂贵。
- 我们总是必须通过模型的方法来创建照片 URL(从 DRY 的角度来看很好,但我们必须使用模型)
代码
生成 URL 的代码如下所示
getPhotoUrl: function() {
return api.getImageUrl(this.id)
}
在 API 中(非常简化)
getImageUrl: function(id) {
var url = "/prefix/something/user/" + id + "/image";
// if we have stored a timestamp, add that to the URL
var noCache = window.localStorage['nocache.'+id];
if (noCache !== undefined) {
url += "?" + noCache;
}
return url;
}
模板代码保持不变:
<!-- render via img.src -->
<img src="<%= user.getPhotoUrl() %>" alt="<%= user.lastname %>" />
<!-- render via CSS background -->
<div class="img" alt="<%= this.shortUsername %>"
style="background-image: url('<%= this.getPhotoUrl() %>')">
...
</div>