Skip to content

Instantly share code, notes, and snippets.

@simenbrekken
Created November 20, 2012 08:45
Show Gist options
  • Select an option

  • Save simenbrekken/4116790 to your computer and use it in GitHub Desktop.

Select an option

Save simenbrekken/4116790 to your computer and use it in GitHub Desktop.
Minimal caching pushState link interceptor
history.pushState && !function() {
var location = history.location || window.location;
var cache = (function() {
var store = {}
return function(key, data) {
if (arguments.length == 2) {
(store[key] = data)
return key
}
return store[key]
}
})()
var fetch = (function() {
var $content = $('.content')
return function(path) {
// Check if we should cache our current content
if (!cache(location.pathname)) {
cache(location.pathname, $content.html())
}
return $.when(cache(path) || $.get(path).done(function(html) {
cache(path, html)
})).done(function(html) {
$content.html(html)
_gaq.push(['_trackPageview', path])
})
}
})()
$(document).on('click', 'a[href^="/"]', function(e) {
var modifier = e.shiftKey || e.metaKey || e.altKey
if (!modifier) {
e.preventDefault()
var path = $(this).attr('href')
// Don't fetch the same page twice
if (location.pathname != path) {
fetch(path).done(function() {
history.pushState({path: path}, document.title, location.protocol + '//' + location.host + path)
})
}
}
})
$(window).on('popstate', function(e) {
e.stopPropagation()
var state = e.originalEvent.state
state && fetch(state.path)
})
}()
@devote

devote commented Nov 20, 2012

Copy link
Copy Markdown
history.pushState({path: path}, document.title, location.protocol + '//' + location.host + path)

@simenbrekken

Copy link
Copy Markdown
Author

@devote Thanks, updated with your protocol suggestion.

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