Skip to content

Commit

Permalink
Revert logic changes, but keep refactors
Browse files Browse the repository at this point in the history
  • Loading branch information
surma committed Dec 7, 2018
1 parent e6ffca9 commit a9d2216
Showing 1 changed file with 17 additions and 26 deletions.
43 changes: 17 additions & 26 deletions src/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -29,21 +29,6 @@ const observer = new IntersectionObserver(entries => {
loaderFunctions.get(url).call(null);
});
});
/**
* Prefetch in-viewport links from a target DOM element. The
* element will be observed using Intersection Observer.
* @param {Object} el DOM element to check for in-viewport links
* @param {Object} options Quicklink options object
* @return {Promise} resolving with list of URLs found
*/
function fetchInViewportLinks(el, options) {
const links = Array.from(el.querySelectorAll('a'));
links.forEach(link => {
observer.observe(link);
});
// Return a list of found URLs
return links.map(link => link.href);
};

/**
* Prefetch an array of URLs if the user's effective
Expand All @@ -69,18 +54,24 @@ export default function (options) {
...options,
};

if (!options.urls) {
options.urls = fetchInViewportLinks(options.el, options);
}
options.timeoutFn(() => {
// If URLs are given, prefetch them.
if (options.urls) {
options.urls.forEach(url => prefetch(url, options.priority));
return;
}

// If not, find all links and use IntersectionObserver.
const linkTags = Array.from(options.el.querySelectorAll('a'));
linkTags.forEach(link => observer.observe(link));
const urls = linkTags.map(link => link.href);

options.urls.forEach(url => {
loaderFunctions.set(url, () => {
loaderFunctions.delete(url);
prefetch(url, options.priority);
// Generate loader functions for each link
urls.forEach(url => {
loaderFunctions.set(url, () => {
loaderFunctions.delete(url);
prefetch(url, options.priority);
});
});
});
options.timeoutFn(() => {
// This is a bit weird, but somehow map access gets transpiled the wrong way.
Array.from(loaderFunctions.values()).forEach(f => f());
}, {timeout: options.timeout});
}

0 comments on commit a9d2216

Please sign in to comment.