Created
November 20, 2012 08:45
-
-
Save simenbrekken/4116790 to your computer and use it in GitHub Desktop.
Minimal caching pushState link interceptor
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
| 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) | |
| }) | |
| }() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment