0

When I make a page, I'm stucking in caching problem. Here is my simplified code.

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

And the point is that :

[Child Html]

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

Whenever I click button and reload the child view, I hope the image, which child view has, change. But since the cached image, the child's image does not change. How can I do for it?

I want to solve it with javascript, since sometimes the jquery version become a big problem and I always consider the version of it. So I want to make my code of small dependance on jQuery. (eg. jquery’s async ajax’s option and so on is not working lower version of IE)

wallah
  • 1,964
  • 5
  • 27
  • 48
  • 2
    I think the cache not of jquery, maybe your backend server caching your images using apache, nginx or maybe Varnish. – Adam Feb 23 '18 at 10:20
  • @Adam might be right, jquery has no cache for images, in order to implement such a cache you would need some sort of preload... so this might be cache by server side, you can use a get with a timestamp at the end probably – juan garcia Feb 23 '18 at 10:23
  • 1
    add a random value in your url (get the current time), it is caused by the webbrowser cache, you can using wireshark to check if the new request is send out. – forqzy Feb 23 '18 at 10:28
  • 1
    Possible duplicate of [Stop jQuery .load response from being cached](https://stackoverflow.com/questions/168963/stop-jquery-load-response-from-being-cached) – Ron van der Heijden Feb 23 '18 at 11:07
  • The server has no cache and I’m trying to solve it in front. Thnak you all !! :) – wallah Feb 23 '18 at 11:25
  • @RonvanderHeijden Also it is very helpful answer I could’nt find ! thank you – wallah Feb 23 '18 at 11:27

1 Answers1

1

You can add the current time as a cache breaker.

$(".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>
Adder
  • 5,708
  • 1
  • 28
  • 56