Created
January 23, 2019 16:03
-
-
Save awayken/f10ff389c668c64fd150ee436fd0bc5d to your computer and use it in GitHub Desktop.
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
// Global maps | |
const preloaded = new Map(); | |
const preloading = new Map(); | |
function buildPreload(url = '') { | |
// If we have a URL | |
if (url.length) { | |
// Create a prefetch <link /> | |
const el = document.createElement('link') | |
el.rel = 'prefetch' | |
el.href = url | |
// Add it to the document head | |
document.head.appendChild(el) | |
} | |
} | |
function clearPreloaded() { | |
preloading.forEach(value => window.clearTimeout(value)) | |
preloading.clear() | |
} | |
function listenPreload(e) { | |
const target = e.currentTarget | |
const targetHref = target.href || null | |
// If this target is laoded or loading, bail. | |
if (!targetHref || preloaded.has(target) || preloading.has(target)) { | |
return | |
} | |
// Actually, the user is interested in this target | |
clearPreloaded() | |
// Add our target to preloading | |
preloading.set(target, window.setTimeout( | |
// After half a second delay | |
() => { | |
// Remove from preloading | |
preloading.delete(target) | |
// Add to preloaded | |
preloaded.set(target, true) | |
// Build the preload <link /> | |
buildPreload(targetHref) | |
}, 500) | |
) | |
} | |
function preloadSection(el) { | |
if (!el) { | |
return; | |
} | |
// Get all of our links from section | |
const links = el.querySelectorAll('a[href^="/"]') | |
for (let link of links) { | |
// Preload on mouseover | |
link.addEventListener('mouseover', listenPreload) | |
} | |
el.addEventListener('mouseleave', ev => { | |
if (ev.currentTarget === el) { | |
// Clear preloaded if we leave the section | |
clearPreloaded() | |
} | |
}) | |
} | |
function preloadMakes() { | |
// Preload the Makes section | |
preloadSection(document.querySelector('[id^="panel_cars-for-sale-by-makes"].js-collapsepanel')) | |
} | |
preloadMakes() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment