Skip to content

Instantly share code, notes, and snippets.

@nirlanka
Last active May 30, 2020 14:48
Show Gist options
  • Save nirlanka/3d95c818d24fef53a83b6fbab0e0aaeb to your computer and use it in GitHub Desktop.
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.)
(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);
}
}
});
}
})();
@nirlanka
Copy link
Author

Draft to add back button support (it's not working yet):

(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;

          if (!(history.state && history.state.prevUrl)) {
            history.pushState({}, document.title, document.location.href);
          }

          history.pushState({ prevUrl: document.location.href }, 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);
        }
      }
    });

    addEventListener('popstate', function(ev) {
      if (history.state && history.state.prevUrl) {
        loadPage(history.state.prevUrl);
      }
    });
  }
})();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment