<main>
  <div>
    
    <h1>Prefetch same-site link on mouse hover</h1>
    <p>Used to load same-site static pages faster.<br>Requires the href attribute to start with a backslash "/".</p>

    <p>No prefetch: &mdash; <a href="https://www.example.com">https href</a> &mdash; <a href="#">Hash href</a> &mdash; <a href="">Empty href</a> &mdash; <a>No href</a></p>
    
    <p>Prefetch: <a href="/">Home</a> &mdash; <a href="/about">About</a> &mdash; <a href="/2kool2/pen/WNXQpGx">Simplerest</a></p>

  </div>
</main>
main > div {
  display: grid;
  min-height: 100vh;
  place-content: center;
  text-align: center;
}
h1 {
  font-size: var(--fs-600);
}
h1 + p:first-of-type {
  font-size: var(--fs-500);
}
console.clear();

const prefetchInternalLinks = event => {
  const target = event.target;

  // Not a link? - if so exit
  if (target.tagName !== 'A') return;

  // Read the attribute rather than the property!
  // - because the property is the full https:// address
  const href = target.getAttribute('href');

  // No href, or not a same-site link? - if so exit
  // - link attribute must start with a backslash
  if (!href || href.charAt(0) !== '/') return;

  // Already prefetched? - if so exit
  const isAlreadyAdded = document.head.querySelector(`link[href="${href}"]`);
  if (isAlreadyAdded) return;

  // Is the same page? - if so exit
  const isSamePage = target.pathname === window.location.pathname;
  if (isSamePage) return;

  // Add prefetch link to head section
  const link = document.createElement('link');
  link.rel = 'prefetch';
  link.href = href;
  document.head.appendChild(link);
};

// Event delegation used as there may be hundreds of same-site links on a page:
document.body.addEventListener('mouseover', prefetchInternalLinks);
Run Pen

External CSS

  1. https://codepen.io/2kool2/pen/WNXQpGx.css

External JavaScript

This Pen doesn't use any external JavaScript resources.