junep
junep

Reputation: 2164

Preventing caching image from jQuery load

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)

Upvotes: 0

Views: 62

Answers (1)

Adder
Adder

Reputation: 5868

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>

Upvotes: 1

Related Questions