Home > Software engineering >  Why browsers fetch images again after reloading my page?
Why browsers fetch images again after reloading my page?

Time:09-28

I am developing a web app, and I want all the images (a couple hundred MB worth - 20 000 - 50 000 thumbnails) to be downloaded once and never downloaded again, as those don't really change. Also, those images are downloaded from youtube servers, and I don't want to hammer their servers unnecessarily.

But the problem is that, when I reload the page, the requests start raining again, instead of loading the cached images. This happens when I navigate to my page and when I reload it, but when I open another page and press back the images are loaded from the cache. When I dynamically add new content with JavaScript the images are loaded from the cache as well.

So, what am I missing?

P.S. I am reloading with the reload button near the address bar, not with Ctrl R or other key combination that cleans the cache.

P.P.S. To clarify before someone comments on that, I am not downloading all those thousands of images at once

CodePudding user response:

For the files in the application that will not change, you can usually add aggressive caching by sending the response header below. This includes static files that are served by the application such as images, CSS files and JavaScript files, for example. In addition, see also the Expires header.

Cache-Control: public, max-age=604800, immutable

MDN Documentation

CodePudding user response:

To answer your question, the best way would be to create a web server (with Node.js, ASP.NET Core, Php, etc.) Your server should save the ressources in a static folder with a max age.

CodePudding user response:

Browsers use the Cache-Control HTTP header to determine if an asset should be retrieved from cache, or downloaded again.

Since you are hotlinking the images from YouTube, you cannot set any HTTP headers; YouTube servers determine the cache settings.

The most straight-forward way to set the cache settings is to first download the images from YouTube and save them on your own server. Then you can set the Cache-Control headers when you serve the images from your server.

Another option may be to proxy the HTTP requests for images from YouTube:

  1. Browser requests image from YourServer.com/image/123.png
  2. YourServer.com serves the image from YouTube.com/img/123.png, using the desired cache headers. An HTTP redirect might work, but this may cause your cache headers to be overridden by YouTube's cache headers. Your server may just have to stream the image data from YouTube.com.
  3. Although the image originated from YouTube.com, the browser will think the image was served from YourServer.com and honor your cache headers.
  • Related