Last active
October 22, 2024 15:10
-
-
Save garraflavatra/7a7fda7053f90b1b9fba82377fc0a709 to your computer and use it in GitHub Desktop.
Speed up webpage loading up to 10x by prefetching links hovered upon.
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
/*! prefetch.js v1.0.1 - Speed up webpage loading by prefetching links hovered upon. | |
(c) Romein van Buren - 2024 - MIT license */ | |
document.addEventListener('DOMContentLoaded', () => { | |
for (const link of document.querySelectorAll('a:not([data-noprefetch])')) { | |
const url = new URL(link.href, 'https://'+window.location.hostname); | |
if (url.hostname !== window.location.hostname || | |
window.location.pathname === url.pathname) continue; | |
const callback = () => { | |
const prefetchLink = document.createElement('link'); | |
prefetchLink.rel = 'prefetch'; | |
prefetchLink.as = 'document'; | |
prefetchLink.href = link.href; | |
document.head.append(prefetchLink); | |
link.removeEventListener('mouseenter', callback); | |
link.removeEventListener('touchstart', callback); | |
}; | |
link.addEventListener('mouseenter', callback); | |
link.addEventListener('touchstart', callback); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment