Skip to content

Instantly share code, notes, and snippets.

@yetimdasturchi
Created May 3, 2022 20:52
Show Gist options
  • Save yetimdasturchi/9646db895b73d6e34ee99b0a90c46726 to your computer and use it in GitHub Desktop.
Save yetimdasturchi/9646db895b73d6e34ee99b0a90c46726 to your computer and use it in GitHub Desktop.
Navigate in site without reloading
var fetchBody = function( url ) {
fetch( url ).then(function (response) {
return response.text();
}).then(function (html) {
var title = html.replace(/^.*?<title>(.*?)<\/title>.*?$/s,"$1");
var body = html.replace(/^.*?<body>(.*?)<\/body>.*?$/s,"$1");
document.title = title;
document.body.innerHTML = body;
history.pushState({page:url}, null, url);
window.scrollTo({ top: 0, behavior: 'smooth' });
run();
}).catch(function (err) {
console.log( 'Error loading' );
});
}
window.addEventListener('popstate', (event) => {
fetchBody( location.href );
});
var run = function() {
var Anchors = document.getElementsByTagName("a");
for (var i = 0; i < Anchors.length ; i++) {
let hostname = new URL(Anchors[i].href);
if (hostname.host == window.location.host) {
Anchors[i].addEventListener("click", function (event) {
fetchBody(this.href);
event.preventDefault();
}, false);
}
}
}
run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment