Last active
May 30, 2020 14:48
-
-
Save nirlanka/3d95c818d24fef53a83b6fbab0e0aaeb to your computer and use it in GitHub Desktop.
Replace body of current static page with another page (without reload) (Note: In this page, <header> isn't considered to change except the <title>. Also, this will mess up the back button, unless you handle window 'popstate' yourself.)
This file contains 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
(function() { | |
if (fetch && Promise && document.querySelector && history) { // <-- Dependencies. Otherwise normal links will remain. | |
function loadPage(url) { | |
fetch(url).then(function (res) { | |
return res.text(); | |
}).then(function(html) { | |
var dom = new DOMParser().parseFromString(html, 'text/html'); | |
var title = dom.querySelector('title').innerText; | |
history.pushState({}, title, url); | |
document.title = title; | |
document.body.innerHTML = dom.querySelector('body').innerHTML; | |
}).catch(err => console.error(err)) | |
} | |
var domain = '//' + document.location.host + '/'; | |
document.body.addEventListener('click', function(ev) { | |
if (ev.target.href) { | |
var idx = ev.target.href.indexOf(domain); | |
if (idx < 6 && idx > -1) { | |
ev.preventDefault(); | |
loadPage(ev.target.href); | |
} | |
} | |
}); | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Draft to add back button support (it's not working yet):