【问题标题】:Preventing caching image from jQuery load防止从 jQuery 加载缓存图像
【发布时间】:2018-08-03 08:59:34
【问题描述】:

当我创建一个页面时,我遇到了缓存问题。这是我的简化代码。

[HTML]

<body>
    <div>here parent contents</div>
    <input id="btn1" class="btn" data-val="1" type="button" />
    <input id="btn2" class="btn" data-val="2" type="button" />
    <input id="btn3" class="btn" data-val="3" type="button" />
    <div id="childContents"></div>
</body>

[javascript]

$(".btn").click(function (e) {
    $("#childContents").load("url?val=" + e.getAttribute("data-val"),
    function () {
        success call back function
    });
});

重点是:

[儿童 Html]

<!-- the image change depanding on some condition -->
<div style="background-image: url('imgUrl')">
    contents
</div>

每当我单击按钮并重新load 子视图时,我希望子视图具有的图像发生变化。 但是由于缓存的图像,孩子的图像并没有改变。我该怎么做呢?

我想用javascript解决它,因为有时jquery版本会成为一个大问题,我总是考虑它的版本。所以我想让我的代码对 jQuery 的依赖很小。 (例如jquery的async ajax的选项等在IE的低版本下不起作用)

【问题讨论】:

  • 我认为缓存不是 jquery,可能是您的后端服务器使用 apache、nginx 或 Varnish 缓存您的图像。
  • @Adam 可能是对的,jquery 没有图像缓存,为了实现这样的缓存,您需要某种预加载...所以这可能是服务器端的缓存,您可以使用最后可能带有时间戳的获取
  • 在你的url中添加一个随机值(获取当前时间),这是由于浏览器缓存造成的,你可以使用wireshark检查是否有新的请求发出。
  • 服务器没有缓存,我在前面尝试解决。谢谢大家!! :)

标签: javascript jquery


【解决方案1】:

您可以将当前时间添加为缓存断路器。

$(".btn").click(function (e) {
    $("#childContents").load("url?val=" + e.getAttribute("data-val"),
    function () {
        //get time since 1970 in milliseonds
        var d = new Date();
        var n = d.UTC();
        //append a cache breaker
        var imgUrl = "background.jpg" + "?t=" + n;
        //set the img url
        $('#backgrounddiv').css('background-image', 'url("'+imgUrl+'")');

    });
});


<div id="backgrounddiv" style="background-image: url('background.jpg')">
    contents
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-23
    • 2011-10-04
    • 2017-01-19
    • 1970-01-01
    • 1970-01-01
    • 2012-04-09
    • 2014-08-13
    • 1970-01-01
    相关资源
    最近更新 更多