Skip to content

Instantly share code, notes, and snippets.

@spraints
Created August 14, 2013 17:45
Show Gist options
  • Save spraints/6233529 to your computer and use it in GitHub Desktop.
Save spraints/6233529 to your computer and use it in GitHub Desktop.
Rails cache + dom manip testing, based on http://www.twmagic.com/misc/cache.html
# add this to app/controllers/application_controller.rb:
def cache
options = {
'no-store' => 'no-store',
'no-cache' => 'no-cache',
'zero-age' => 'max-age=0',
}
if cc = options[params[:id]]
headers['Cache-Control'] = cc
end
html = Rails.root.join('app/views/shared/cache.html').read
html.sub!(/CURRENTTIME/, Time.now.to_s)
html.sub!(/OPTIONS/, options.inject(%Q{<li><a href="/cache">max-age=0, private, must-revalidate (rails default)</a></li>}) { |h, (id,value)| h << %Q{<li><a href="/cache/#{id}">#{value}</a></li>} })
render :text => html
end
<!-- Save this to app/views/shared/cache.html -->
<!doctype html>
<script type="text/javascript">
function addText(text) {
var ul = document.getElementById('ul');
var li = document.createElement('li');
li.appendChild(document.createTextNode(text));
ul.appendChild(li);
}
function callback() {
}
function modifyDOM() {
addText("Here is a new list item!");
return false;
}
function addUnload() {
window.onunload = callback;
addText("onunload handler installed");
return false;
}
function addBeforeUnload() {
window.onunload = callback;
addText("onbeforeunload handler installed");
return false;
}
window.onload = function() {
addText('window loaded');
}
</script>
<title>Back/Forward Cache Test</title>
<p><a href="/404">Go to another page</a></p>
<p><a href="#" onclick="return modifyDOM()">Modify the DOM</a></p>
<p><a href="#" onclick="return addUnload()">Add onunload handler</a></p>
<p><a href="#" onclick="return addBeforeUnload()">Add onbeforeunload handler</a></p>
<ul id="ul">
<li>This page was sent with headers allowing it to be cached.</li>
<li>This page was loaded from the server at CURRENTTIME</li>
</ul>
<h3>Cache-control options</h3>
<ul>OPTIONS</ul>
# add this to config/routes.rb:
get 'cache(/:id)' => 'application#cache'
@spraints
Copy link
Author

I'm looking for something that either reloads from the server or preserves DOM changes. It doesn't have to do both, but it has to do one or the other.

None of the cache-control settings get Chrome to preserve DOM changes. It always drops them. Only Cache-Control: no-store makes Chrome reload the page from the server, so that's what I'm going to use.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment