Skip to content

Instantly share code, notes, and snippets.

@garraflavatra
Last active October 22, 2024 15:10
Show Gist options
  • Save garraflavatra/7a7fda7053f90b1b9fba82377fc0a709 to your computer and use it in GitHub Desktop.
Save garraflavatra/7a7fda7053f90b1b9fba82377fc0a709 to your computer and use it in GitHub Desktop.
Speed up webpage loading up to 10x by prefetching links hovered upon.
/*! 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