I've modified a code I did few ago for a style guide adding it a pjax navigation. I liked the idea of your request, it's not a bad idea, but that need some options like, not caching every link on the page, detect external pages etc, but feel free to use it.
There's still some console debug, it's a bit raw, and using jQuery.
var SPAajaxloading = function () {
var $links = $('#nav a');
var historyCache = {};
var getCache = function (url) {
return historyCache[url];
};
var setCache = function (url, content) {
historyCache[url] = content;
};
var setContent = function (content, URL) {
$('#content').html(content);
history.pushState(null, null, URL);
};
var getFragmentContent = function (responsecontent) {
var $fakediv = $('<div>');
$fakediv.html(responsecontent);
return $fakediv.find('#content').html();
};
var getPageContent = function (URL, caching) {
return $.ajax({
url: URL
}).promise().done(function (response) {
var _content = getFragmentContent(response);
!caching && setContent(_content, URL);
setCache(URL, _content);
});
};
var linkbinding = function (e) {
e.preventDefault();
var _URL = this.href;
var cachedContent = getCache(_URL);
//todo refactor this with popstate
if (e.type === 'click' && cachedContent) {
console.info('content inserted via cache');
setContent(cachedContent, _URL);
}
else {
// if mouseenter and cache is here, do nothing
if (e.type === 'mouseenter' && cachedContent) {
console.info('nothing to do, caching already done');
}
else {
console.info('putting content in cache?', e.type === 'mouseenter');
getPageContent(_URL, e.type === 'mouseenter')
}
}
};
$links.on('mouseenter click', linkbinding);
setCache(location.href, $('#content').html());
$(window).on('popstate', function () {
var _URL = location.href;
var content = getCache(_URL);
if (content) {
setContent(content, _URL);
}
else {
getPageContent(_URL)
}
});
};
I just posted it on gisthub, if you want to improve this, or maybe why not starting another github project on PJAX loading tell me, I'm open to go further on this!
https://gist.github.com/romuleald/bc7d4a941f42f8e4bc0e