Skip to content

Instantly share code, notes, and snippets.

@romuleald
Created April 15, 2015 09:38
Show Gist options
  • Save romuleald/bc7d4a941f42f8e4bc0e to your computer and use it in GitHub Desktop.
Save romuleald/bc7d4a941f42f8e4bc0e to your computer and use it in GitHub Desktop.
PJAX with caching on mouseenter
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)
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment