Rails 3 full page caching on Heroku

Recently I implemented full page caching on this blog. Not because of the insane amount of traffi...

Tips for dynamic CSS themes using jQuery

I recently added a dark theme to this blog, it's great for night time reading on your laptop,...

0
Friday, November 30, 2012
Caching dynamic partials when using Turbolinks

Yesterday I blogged about caching and loading dynamic partials via ajax for non static content. This can sometimes defeat the purpose of caching content if you are hitting the rails stack and accessing the database each time the page loads via ajax.

Turbolinks only loads assets on the original page load, after that it just replaces the body content. This gave me an idea. Load my dynamic partials only on a real page load and not everytime Turbolinks requests a new page.

Caching

Outside of any document ready methods (usually top of your main application js/coffee file) I place my cache holder variables. In this example I will show you how I load and cache the recent posts on this blog.

window.cachedRecentPosts = ''

Then in the document ready and Turbolinks 'page:load' event I check to see if there is anything in the cache holder. If there is I just populate the html with the cached content or call the script via ajax to get the new content.

# Load recent posts
if window.cachedRecentPosts != ''
  $('ul.recent-posts').append(window.cachedRecentPosts)
else
  $.getScript('/pages/recent_posts')

When /pages/recent_posts is called via $.getScript() it loads app/views/pages/recent_posts.js.erb which will populate the window.cachedRecentPosts variable with the recent posts and also populate the html with the content.

window.cachedRecentPosts = '<%= j render("layouts/recent_posts") %>';
$('ul.recent-posts').append(window.cachedRecentPosts);

The above script will only be called on the original page load with subsequent requests using the cached content greatly improving the speed of the page and lessening the load on the server.

Tweet this post if you found it useful

Related Posts

Rails 3 full page caching on Heroku

Wednesday, November 28, 2012  ·   2

Recently I implemented full page caching on this blog. Not because of the insane amou... (continued)

Resetting JavaScript variables when using Turbolinks

Saturday, December 1, 2012  ·   0

Every time you load a new page with Turbolinks only the body of the page is replaced.... (continued)

Introducing Polytalk. A simple protocol which allows communication between different languages via TCP.

Monday, November 26, 2012  ·   0

Polytalk is my latest open source project. I developed it out of the need to communic... (continued)

Building a simple single page application using AngularJS

Tuesday, December 4, 2012  ·   0

I am going to walk you through building a SPA (single page application) using Angular... (continued)

0 Comments

Comment successfully added. View comment.×

Comments are now closed for this article.