Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to leverage browser caching in Rails 4?

I am using GTMetrix to see my site speed and it is showing me this (check below image).

How can I Leverage browser caching to speed up the site loading speed in Rails 4?

To defer parsing JS, I have already put

<%= javascript_include_tag 'application' %>

before /html tag.

enter image description here

like image 419
iCyborg Avatar asked Jan 19 '17 12:01

iCyborg


People also ask

How do I leverage browser caching?

Leveraging Browser Cache Using . First thing first, you can leverage browser caching by modifying the . htaccess file. To do so, you can use an FTP client like FileZilla or the file manager in your hosting control panel. This method might suit you well if you're an advanced user.

How do I cache a page in Rails?

In order to use page and action caching you will need to add actionpack-page_caching and actionpack-action_caching to your Gemfile . By default, caching is only enabled in your production environment. You can play around with caching locally by running rails dev:cache , or by setting config. action_controller.

How do I use Redis cache Rails?

To use Redis as a Rails cache store, use a dedicated cache instance that's set up as an LRU (Last Recently Used) cache instead of pointing the store at your existing Redis server, to make sure entries are dropped from the store when it reaches its maximum size.


1 Answers

I would recommend using separate web server, like NGINX to set cache headers for .js and .css files, removing the hassle of serving static files from Rails.

If you really wanna go with a pure Rails (app/web)server, the solution is putting this piece of code in config/environments/production.rb

RAILS 5

config.public_file_server.headers = {
  'Cache-Control' => "public, s-maxage=#{365.days.to_i}, maxage=#{180.days.to_i}",
  'Expires' => "#{1.year.from_now.to_formatted_s(:rfc822)}"
}

RAILS 4

config.static_cache_control = "public, s-maxage=#{365.days.to_i}, maxage=#{180.days.to_i}"
like image 62
ErvalhouS Avatar answered Sep 29 '22 15:09

ErvalhouS