Skip to content

Instantly share code, notes, and snippets.

@bryfox
Created October 24, 2011 03:11
Show Gist options
  • Save bryfox/1308282 to your computer and use it in GitHub Desktop.
Save bryfox/1308282 to your computer and use it in GitHub Desktop.
One quick & dirty approach for an offline-friendly, frequently-updated page that doesn't require JS.
<!DOCTYPE html>
<html manifest="cache.appcache">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<h1>FreshAppCache</h1>
<h2>Requirements:</h2>
<ul>
<li>A cached version of this page is visible without an active network connection</li>
<li>There is data on the page that is frequently updated, so...</li>
<li>When a network connection is available, the latest content should be shown</li>
</ul>
<h2>Here's our data:</h2>
<div id="server_content">
<ul>
<li>Tartan 3: <%= Time.now.to_f %></li>
<li>Tartan 2</li>
<li>Tartan 1</li>
</ul>
</div>
<script type="text/javascript" charset="utf-8">
var appCache = window.applicationCache,
$content = $('#server_content');
ensureFreshContent();
function ensureFreshContent () {
// If browser doesn't support cache manifest, move along.
// Note that we could (TODO) implement some sort of caching solution using
// various local storage mechanisms for browsers that support, say,
// IE User Data, but not HTML5 cache manifests
if (!appCache) return;
// Otherwise, hide the content until we know we have the latest
// (TODO: display a loading indicator)
$content.hide();
// If there's nothing to update, we'll show the cached version
appCache.addEventListener('cached', showCached, false);
appCache.addEventListener('error', showCached, false);
appCache.addEventListener('noupdate', showCached, false);
appCache.addEventListener('obsolete', showCached, false);
// But if we recognize an update, swap out the cache & display it.
appCache.addEventListener('updateready', updateDisplay, false);
// Kick off the update
appCache.update();
}
function showCached (evt) {
$content.show();
}
function updateDisplay (evt) {
appCache.swapCache();
// This is a bit brute-force...
// If update took some time, then this could be jarring
// An alternative would be to load another resource (AJAX)
// that only gave us the updated content we need
window.location = window.location;
}
</script>
</body>
</html>
CACHE MANIFEST
# Updates every ten seconds
# v<%= (Time.now.to_f/10).round * 10 %>
CACHE:
/
NETWORK:
*
class Site < Sinatra::Base
get '/' do
erb :index
end
get '/cache.appcache' do
headers['Content-Type'] = 'text/cache-manifest'
erb :'cache.appcache'
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment