Created
January 24, 2013 09:42
-
-
Save alexedwards/4619251 to your computer and use it in GitHub Desktop.
Ajax content loading with Sinatra, jQuery and HTML5 Pushstate.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'sinatra' | |
before do | |
response['Cache-Control'] = 'no-cache, no-store' if request.xhr? | |
end | |
get '/' do | |
erb :home, layout: ! request.xhr? | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(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