Skip to content

Commit

Permalink
Clean-up source
Browse files Browse the repository at this point in the history
  • Loading branch information
addyosmani committed Nov 23, 2018
1 parent 67784f7 commit ecbd70f
Show file tree
Hide file tree
Showing 4 changed files with 67 additions and 4 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "quicklink",
"version": "0.0.1",
"description": "Faster page-loads by prefetching links during idle time",
"main": "index.js",
"main": "src/index.mjs",
"repository": "/~https://github.com/addyosmani/quicklink.git",
"author": "addyosmani <addyosmani@gmail.com>",
"license": "Apache-2.0",
Expand Down
7 changes: 4 additions & 3 deletions index.mjs → src/index.mjs
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import prefetch from './prefetch.mjs';
import requestIdleCallback from './request-idle-callback.mjs';

/**
*
* @param urls Array of URLs to prefetch
Expand Down Expand Up @@ -63,6 +66,4 @@ export default function quicklink(options) {
});
}
});
}

// TODO: add preload / high prio?
}
47 changes: 47 additions & 0 deletions src/prefetch.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
const support = function(feature) {
if (typeof document === `undefined`) {
return false
}
const fakeLink = document.createElement(`link`)
try {
if (fakeLink.relList && typeof fakeLink.relList.supports === `function`) {
return fakeLink.relList.supports(feature)
}
} catch (err) {
return false
}
}
const linkPrefetchStrategy = function(url) {
if (typeof document === `undefined`) {
return
}
const link = document.createElement(`link`)
link.setAttribute(`rel`, `prefetch`)
link.setAttribute(`href`, url)
const parentElement =
document.getElementsByTagName(`head`)[0] ||
document.getElementsByName(`script`)[0].parentNode
parentElement.appendChild(link)
}
const xhrPrefetchStrategy = function(url) {
const req = new XMLHttpRequest()
req.open(`GET`, url, true)
req.withCredentials = true
req.send(null)
}

const supportedPrefetchStrategy = support(`prefetch`)
? linkPrefetchStrategy
: xhrPrefetchStrategy

const preFetched = {}

const prefetch = function(url) {
if (preFetched[url]) {
return
}
preFetched[url] = true
supportedPrefetchStrategy(url)
}

export default prefetch
15 changes: 15 additions & 0 deletions src/request-idle-callback.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// RIC and shim for browsers setTimeout() without it
const requestIdleCallback = 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);
}

export default requestIdleCallback;

0 comments on commit ecbd70f

Please sign in to comment.