Created
February 1, 2019 02:48
-
-
Save mrsweaters/0aecfa2049ac4f7a381b39b05f4a01af to your computer and use it in GitHub Desktop.
TurboLinks with Prefetch on Hover
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
const hoverTime = 300; | |
const fetchers = {}; | |
function prefetch(url) { | |
const iframe = document.createElement('iframe'); | |
iframe.hidden = true; | |
iframe.src = url; | |
iframe.addEventListener('load', () => { | |
const snapshot = Turbolinks.Snapshot.fromHTMLElement(iframe.contentDocument.documentElement); | |
Turbolinks.controller.cache.put(url, snapshot); | |
}); | |
document.body.appendChild(iframe); | |
} | |
function prefetched(url) { | |
return Turbolinks.controller.cache.has(url); | |
} | |
function cleanup(event) { | |
const element = event.target; | |
clearTimeout(fetchers[element.href]); | |
element.removeEventListener('mouseleave', cleanup); | |
} | |
document.addEventListener('mouseover', event => { | |
if (!event.target.dataset.prefetch) return; | |
let url = event.target.href; | |
if (prefetched(url)) return; | |
cleanup(event); | |
event.target.addEventListener('mouseleave', cleanup); | |
fetchers[url] = setTimeout(() => prefetch(url), hoverTime); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment