-
Notifications
You must be signed in to change notification settings - Fork 412
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
fd6149b
commit ce0aa40
Showing
1 changed file
with
56 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
/** | ||
* | ||
* @param urls Array of URLs to prefetch | ||
*/ | ||
function fetchLinks(urls) { | ||
urls.forEach((url) => { | ||
prefetch(url); | ||
}); | ||
} | ||
|
||
/** | ||
* Extract only links that are in the visible viewport | ||
* @param el DOM element to check for in-viewport links | ||
*/ | ||
function extractInViewportLinks(el) { | ||
return new Promise((resolve, reject) => { | ||
const urls = []; | ||
const links = el.querySelectorAll('a'); | ||
const observer = new IntersectionObserver(entries => { | ||
entries.forEach(entry => { | ||
// Link is in the view | ||
if (entry.intersectionRatio > 0) { | ||
urls.push(entry.target.href); | ||
} else { | ||
// Link is out of the view | ||
} | ||
}); | ||
resolve(urls); | ||
}); | ||
links.forEach(link => { | ||
observer.observe(link); | ||
}); | ||
}); | ||
} | ||
|
||
/** | ||
* | ||
* @param options | ||
* options.urls: Array of URLs to prefetch (override) | ||
* options.el: DOM element to prefetch in-viewport links of | ||
*/ | ||
export default function quicklink(options) { | ||
options = options || {}; | ||
requestIdleCallback(() => { | ||
// Prefetch an array of URLs if supplied (as an override) | ||
if (options.urls !== undefined && options.urls.length > 0) { | ||
fetchLinks(options.urls); | ||
} else { | ||
// Element to extract in-viewport links for | ||
let el = options.el || document; | ||
extractInViewportLinks(el).then((urls) => { | ||
fetchLinks(urls); | ||
}); | ||
} | ||
}); | ||
} |