Skip to content

Instantly share code, notes, and snippets.

@evolify
Created September 27, 2023 02:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save evolify/aafced6efad730ad92cdd82370315ed0 to your computer and use it in GitHub Desktop.
Save evolify/aafced6efad730ad92cdd82370315ed0 to your computer and use it in GitHub Desktop.
web
function prefetch(nodeLists) {
// Exclude slow ECTs < 3g
if (
navigator.connection &&
(navigator.connection.effectiveType === "slow-2g" ||
navigator.connection.effectiveType === "2g")
) {
return;
}
// Exclude low end device which is device with memory <= 2GB
if (navigator.deviceMemory && navigator.deviceMemory <= 2) {
return;
}
const fetchLinkList = {};
const observer = new IntersectionObserver(function (entries) {
entries.forEach(function (entry) {
if (entry.isIntersecting) {
if (!fetchLinkList[entry.target.href]) {
fetchLinkList[entry.target.href] = true;
fetch(entry.target, {
priority: "low",
});
}
observer.unobserve((entry = entry.target));
}
});
});
}
const idleCallback =
window.requestIdleCallback ||
function (cb) {
let start = Date.now();
return setTimeout(function () {
cb({
didTimeout: false,
timeRemaining: function () {
return Math.max(0, 50 - (Date.now() - start));
},
});
}, 1);
};
idleCallback(function () {
prefetch(nodeLists);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment