How can I cache background images (forcefully) in user’s browser.
It will great to set a expiry time of 1 week or 1 month something.
PS:I have a page which shows listing based upon category. Every category has its own background image and I want to cache those background images.Every image is something about 20-30kb and I have some 20 categories.
Varnish is a solution and here is the gem which can help you in implementing it
Install
This gem requires ruby 1.9
Basic installation
config/initializers/lacquer.rb
app/controllers/application_controller.rb
config/varnishd.yml
If only some urls of the application should be cached by varnish, Lacquer::CacheControl will be helpful.
config/initializers/caches.rb
In the sweeper we can do something like this
This will purge “^(/[a-z]{2})?/class_sections/1/open_scoring.*$” (/sv/class_sections/1/open_scoring.js, /sv/class_sections/1/open_scoring.html)
The varnish.vcl is preprocssed when starting varnishd with the rake tasks
config/varnish.vcl.erb
This makes it much simpler to perform cacheing, it’s only setuped in one place, purge it or just let it expire.
Usage
To set a custom ttl for a controller:
Clearing the cache:
Control varnishd with the following rake tasks
Gotchas
The default TTL for most actions is set to 0, since for most cases you’ll probably want to be fairly explicit about what pages do get cached by varnish. The default cache header is typically:
Cache-Control: max-age=0, no-cache, private
This is good for normal controller actions, since you won’t want to cache them. If TTL for an action is set to 0, it won’t mess with the default header.
The key gotcha here is that cached pages strip cookies, so if your application relies on sessions and uses authenticity tokens, the user will need a session cookie set before form actions will work. Setting default TTL to 0 here will make sure these session cookies won’t break.
As a result, all you have to do to set a cacheable action is the before filter above.