0

I have an Image container which will dynamically be filled with image tag after AJAX request. The AJAX code is as simple as below and it run after the page fully loaded.

 $(document).ready(function () {
    $.ajax({
        url: '/product/GetImageUrl',
        type: 'GET',
        data: { id: id },
        success: function (result) {
              var imageBox = $('#image-container');
              imageBox.append('<img src="' + result.ImageUrl + '">')
        }
    });
 });

The AJAX is only request the image URL. I see the image is successfully loaded.

However, when I refresh the page, the browser keeps downloading the image, although the URL is still the same.

What should I do to tell browser to cache the image URL?

  • This entirely depends on the cache headers that apply to the image URL. – Phil Sep 02 '22 at 02:09
  • Have you determined through your browsers dev-tools _Network_ panel that the image is being retrieved fresh? If cache headers are set correctly, you should see the response as a 304 - Not Modified – Phil Sep 02 '22 at 02:11
  • 1
    @Phil I don't see Cache-Control in the Response Header of the URL. But, what make it weird is because if I hardcoded to the URL to the page, the image is cached and loaded instantly together with page. Only if I added the URL later using AJAX, the image URL not cached. I see the response code is 200 in both hardcoded URL and adding by AJAX. Also, both has the same Response Header. – Fari Fairis Sep 02 '22 at 02:21
  • @Phil So, I think I need some mechanism to manually add the image URL to browser cache. – Fari Fairis Sep 02 '22 at 02:22
  • 1
    Check that you haven't turned off jquery's ajax cache anywhere. See this question/answer which essentially asks the opposite of what you've asked: [prevent browser caching of ajax calls](https://stackoverflow.com/questions/367786/prevent-browser-caching-of-ajax-call-result) – freedomn-m Sep 02 '22 at 04:54

0 Answers0