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.
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.