Created
August 31, 2022 23:22
-
-
Save leouofa/08f1c59dcd9fd6ea0868d27baf046506 to your computer and use it in GitHub Desktop.
Hover link preloading w/ Stimulus & Turbo
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
// Responsible for preloading links | |
// Based on this https://gist.github.com/vitobotta/8ac3c6f65633b5edb2949aeff0dec69b | |
// Uses https://github.com/stimulus-use/stimulus-use | |
import { Controller } from '@hotwired/stimulus' | |
import { useHover } from 'stimulus-use' | |
export default class extends Controller { | |
connect() { | |
useHover(this, { element: this.element }); | |
this.url = this.element.getAttribute("href") | |
this.loc = new URL(this.url, location.protocol + "//" + location.host) | |
this.absoluteUrl = this.loc.toString() | |
this.delayOnHover = this.data.get('delay') | |
this.mouseoverTimer | |
} | |
mouseEnter() { | |
this.mouseoverTimer = setTimeout(() => { | |
this.preload() | |
this.mouseoverTimer = undefined | |
}, this.delayOnHover) | |
} | |
mouseLeave() { | |
clearTimeout(this.mouseoverTimer) | |
this.mouseoverTimer = undefined | |
} | |
fetchPage (url, success) { | |
const xhr = new XMLHttpRequest() | |
xhr.open('GET', url) | |
xhr.setRequestHeader('VND.PREFETCH', 'true') | |
xhr.setRequestHeader('Accept', 'text/html') | |
xhr.onreadystatechange = () => { | |
if (xhr.readyState !== XMLHttpRequest.DONE) return | |
if (xhr.status !== 200) return | |
success(xhr.responseText) | |
} | |
xhr.send() | |
} | |
preload() { | |
if (!Turbo.navigator.view.snapshotCache.has(this.loc)) { | |
this.fetchPage(this.url, responseText => { | |
const snapshot = Turbo.PageSnapshot.fromHTMLString(responseText) | |
Turbo.navigator.view.snapshotCache.put(this.loc, snapshot) | |
}) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment