Search code examples
ruby-on-railsgoogle-chromecachingassets

Google Chrome is not caching images


I'm trying to optimize my application in Ruby on Rails, and I realized that the pictures in my application is what most long does it take to load, but I also noticed another problem, which is that google chrome isn't caching the images.

I noted this because in the Google Developers Console you can see that Google Chrome makes a request to load the images that are canceled before the images are truly loaded.

This can be seen here, first I open the Google Developers Console, then refresh the page and within the first requests there you can see the ones of the images, but they are canceled immediately.

google_not_caching

After that you can see the requests that actually loaded the images.

enter image description here

I don't understand why is this happening if in the response headers you can see that the Cache Control is set to public with max-age = 31536...

response_header

I put the images in my application this way:

<div class="col-xs-3"><%= image_tag "#{@hero.id}/ability_1.png", class: "center-block"%></div>

And the images are organized in folders in app/assets/images

Is there a RoR way to fix this?

Edit: Now testing my app (which is in Heroku) in Windows I noticed that in fact Google Chrome caches the images sometimes, but it happens like the 50% of the times (and when I was in Ubuntu in development it didn't work a single time), while in firefox the first time the images are loaded, but the subsequent times I load the same view I can't even notice the reload, it's beatiful, Why google Chrome is not like that? Is normal that Google Chrome acts so weird?


Solution

  • The most important thing to realize when analyzing browser caching is the "Status Code". In your example, you can see you got a "304", which stands for "Not Modified" Which means the browser "could potentially use it's cache". So you ARE in fact caching. Caching != Not hitting your web server.

    The definition according to Mozilla:

    This is used for caching purposes. It is telling to client that response has not been modified. So, client can continue to use same cached version of response.

    It sends the etag and last-modified to your web server, and your web server then looks at those meta and say "Nope, this file hasn't changed, so feel free to use your cache", and that's it. It actually does not send the file again. You can see that the "Size" is much less then when it's a "200" status code, where the web server IS sending the file, and the timing should me much shorter as well.

    In Chrome you can force "non-caching" by checking the "Disable cache" option in the Network tab.

    Hope that helps!