Created
June 1, 2023 01:00
-
-
Save angelogladding/ad2f42adc9db54f7ce84926a65e585b7 to your computer and use it in GitHub Desktop.
spa.js
This file contains hidden or 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
| const SELECTOR = '#main' | |
| const currentContainer = document.querySelector(SELECTOR) | |
| const upgradeLinks = links => { | |
| for (let i = 0; i < links.length; i++) { | |
| links[i].addEventListener('click', event => { | |
| event.preventDefault() | |
| const url = this.href | |
| const scroll = 0 | |
| history.replaceState({scroll: window.pageYOffset}, null, window.location.href) | |
| updatePage(url, scroll) | |
| history.pushState({scroll: scroll}, null, url) | |
| }) | |
| } | |
| } | |
| const updatePage = (url, scroll) => { | |
| const req = new XMLHttpRequest() | |
| req.onreadystatechange = function() { | |
| if (req.readyState === 4) { | |
| const newContainer = new DOMParser() | |
| .parseFromString(req.response, 'text/html') | |
| .querySelector(SELECTOR) | |
| currentContainer.innerHTML = newContainer.innerHTML | |
| document.body.scrollTop = document.documentElement.scrollTop = scroll | |
| setLinkHandlers(currentContainer.querySelectorAll('a')) | |
| } | |
| } | |
| req.open('GET', url) | |
| // XXX req.setRequestHeader('X-Chromeless', 'true') | |
| req.send() | |
| } | |
| window.addEventListener('popstate', event => { | |
| if (event.state === null) | |
| return | |
| updatePage(window.location.href, event.state.scroll) | |
| }) | |
| upgradeLinks(document.querySelectorAll('a')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment