Skip to content

Instantly share code, notes, and snippets.

@angelogladding
Created June 1, 2023 01:00
Show Gist options
  • Select an option

  • Save angelogladding/ad2f42adc9db54f7ce84926a65e585b7 to your computer and use it in GitHub Desktop.

Select an option

Save angelogladding/ad2f42adc9db54f7ce84926a65e585b7 to your computer and use it in GitHub Desktop.
spa.js
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