Tony Beninate
Tony Beninate

Reputation: 1985

Caching external images with Rails fragment caching

I am using Rails' fragment caching to cache these individual "widgets" which were turning out to be pretty hefty calls

<%= render partial: 'championships/championship', collection: @championships, cached: true %>

It is all working fine and as expected. However another reason for doing this is that each widget makes a call for an image which is externally hosted on Uploadcare and I wanted to reduce the number of calls we were making there. However, when I load the page and look at Network requests, I am still seeing requests to Uploadcare for each of these images.

enter image description here

Am I mis-reading this? Are these possibly just being recalled from cache or are they actually making the external request? Is there any way to include these external images in the fragment caching?

https://www.redlinemotorsport.co.uk

Thank you

Upvotes: 1

Views: 1568

Answers (2)

Dmitry Mukhin
Dmitry Mukhin

Reputation: 6937

enter image description here

You're getting those from browser memory (cache). At Uploadcare we're working hard on improving web performance, so unless you're doing anything weird, browsers will cache your images for good :)

Upvotes: 1

edariedl
edariedl

Reputation: 3352

I don't know how your championship partial looks like, but I would expect, that there is something like this for images:

<img src="https://example.com/image.jpg" alt="alt">

or image_tag if it is in the rails helper.

In this case, only this tag is cached, not image itself. Image is then downloaded by the browser during HTML processing and rendering.

Fragment caching is probably not the right way for image caching. Don't get me wrong, you can cache images with fragment caching, but you would have to embed the image directly into the view, not just images URL address. It looks something like this:

<img src=”data:<MIMETYPE>;base64,<BASE64_ENCODED_IMAGE>”>

More info about it can be found eg here: https://www.bigfastblog.com/embed-base64-encoded-images-inline-in-html. Image would be embedded directly into the view and cached with the HTML fragment. But it is not usable for images from the external websites and you probably shouldn't do it anyway.

It is true that browser will do a lot of requests to the external sites (CDN) but on the other hand it will usually use HTTP Caching, it only downloads new or changed images. Rest of the images are only checked whether they have been changed, if they haven't, they won't be downloaded again, they will be loaded from the browser cache.

Upvotes: 3

Related Questions