Skip to content

Commit

Permalink
Adds index: initial implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
addyosmani committed Nov 23, 2018
1 parent fd6149b commit ce0aa40
Showing 1 changed file with 56 additions and 0 deletions.
56 changes: 56 additions & 0 deletions index.mjs
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);
});
}
});
}

0 comments on commit ce0aa40

Please sign in to comment.