Skip to content

Instantly share code, notes, and snippets.

@alexedwards
Created January 24, 2013 09:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexedwards/4619251 to your computer and use it in GitHub Desktop.
Save alexedwards/4619251 to your computer and use it in GitHub Desktop.
Ajax content loading with Sinatra, jQuery and HTML5 Pushstate.
require 'sinatra'
before do
response['Cache-Control'] = 'no-cache, no-store' if request.xhr?
end
get '/' do
erb :home, layout: ! request.xhr?
end
<!doctype html>
<html lang='en-GB'>
<head>
<meta charset='utf-8'>
<title></title>
<meta name='description' content=''>
<meta name='robots' content=''>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>
<script src='/javascripts/script.js'></script>
<link rel='stylesheet' href='/stylesheets/style.css'>
</head>
<body>
<header>
<nav>
<ul>
<li><a id='home' href='/'>Home</a></li>
</ul>
</nav>
</header>
<div id='content' class='wrapper'>
<%= yield %>
</div>
</body>
</html>
$(document).ready(function() {
if (typeof history.pushState === 'function') {
$('nav a').click(function(e) {
href = $(this).attr('href');
$('nav a').removeClass('current');
$('nav a[href="' + href + '"]').addClass('current');
$('#content').fadeOut(0, function(){
$('#content').load(href, function(){
$(this).fadeIn(0);
});
history.pushState(null, '', href);
});
e.preventDefault();
});
window.onpopstate = function (e) {
$('#content').load(window.location.pathname);
e.preventDefault();
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment