prefetching for dummies
A friend of mine vibe coded a web design service in a few hours, and the first thing I’ve noticed is that it’s fast. Tapping links on mobile lands to a new page instantaneously.
Not one to want to use React or Vercel or ✨vibes✨, I’ve written a snippet which will (on connections better than ‘2G’) prefetch any links visible in the viewport:
const connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection
if (connection) {
const isSlowConnection = connection.effectiveType.includes('2g') || connection.saveData
if (!isSlowConnection) {
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const href = entry.target.getAttribute('href')
if (href) {
const url = new URL(href, location.origin) // Resolve relative URLs
if (url.hostname === location.hostname) { // Only same-origin
const prefetch = document.createElement('link')
prefetch.rel = 'prefetch'
prefetch.href = url.href
document.head.appendChild(prefetch)
observer.unobserve(entry.target) // Only preload once
}
}
}
})
})
document.querySelectorAll('a').forEach(link => observer.observe(link))
}
}