Caching Locale-specific Dynamic JavaScript Files
I was recently inspired to create some cached, dynamic JavaScript files for a project I am working on after watching Ryan Bates Railscasts episodes 88 and 89.
The basic concept is to create a JavaScript controller that dynamically renders some JavaScript file(s). This allows you to take advantage of ERB in your JavaScript files. However, this can become slow as every request for that JavaScript file must be processed by Rails. In episode 89, Ryan showed how to cache the dynamic JavaScript file to improve performance. These episodes were great, except I had one problem… The dynamic portion of the JavaScript files I was working with were translated strings.
This meant that I couldn’t just cache the JavaScript file because the translation would need to be different based on the locale setting of the user. It turns out there’s a pretty easy solution to this. If you follow the lessons from the episodes then you will have a general caching mechanism for the dynamic JavaScript files. Assuming you are using a translation mechanism like Globalize then you have access to a locale for the current session. Simply use this locale when including the JavaScript file (e.g., dynamic_states):
Your layout file
<%= javascript_include_tag "#{locale}/dynamic_states" -%>
This will try to include the dynamic_states.js file from the javascripts/locale directory where locale is something like en, es, zh, etc. The only other thing to do is define a custom route to handle this new pattern.
routes.rb
map.connect ':controller/:locale/:action.:format'
That’s it. You should now have locale-specific dynamic JavaScript files. For what I was working on, I also nested the locale directory within another directory (e.g., cache) just for ease of removal in case you need to wipe out the entire cache of dynamic JS.
Resources
More of my rantings
These might also interest you
- Everything A Django Developer Needs To Create Logins (Aware Labs)
- Drupal vs. WordPress for Geo (Adam Estrada)
- Custom Actions In Django Admin Object Editor (Aware Labs)
I am completely agreed with you that dynamic caching is the ultimate solution for the problems like Scalability, Performance and Reliability. I have found another article on internet which also talks about the Benefits of Dynamic Caching. I am sure this can be a good read for all the readers who are interested in dynamic caching.
December 1st, 2009 at 8:13 am