Skip to content

Instantly share code, notes, and snippets.

@wpsmithtwc
Created September 28, 2017 14:35
Show Gist options
  • Save wpsmithtwc/557b2152311be299cd73f7cb1ec209ce to your computer and use it in GitHub Desktop.
Save wpsmithtwc/557b2152311be299cd73f7cb1ec209ce to your computer and use it in GitHub Desktop.
JavaScript: Resource Hinting
(function() {
let isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0,
// Chrome 1+
isChrome = !!window.chrome && !!window.chrome.webstore;
console.log("isChrome: ", isChrome);
console.log("isOpera: ", isOpera);
function linkPreload(as, url) {
let l = document.createElement("link");
l.rel = "preload";
l.as = as;
l.crossOrigin = "";
l.href = url;
document.head.appendChild(l);
}
function linkPrerender(url) {
let l = document.createElement("link");
l.rel = "prerender";
l.href = url;
document.head.appendChild(l);
}
function linkPrefetch(url) {
let l = document.createElement("link");
l.rel = "prefetch";
l.as = "html";
l.crossOrigin = "";
l.href = url;
document.head.appendChild(l);
}
function linkPreconnect(url) {
let l = document.createElement("link");
l.rel = "preconnect";
l.crossOrigin = "";
l.href = url;
document.head.appendChild(l);
}
let resourceHints = {
"preconnect": ["example.com", "sub1.example.com", "sub2.example.com", "anotherexample.com", "anotherexample.com", "fonts.gstatic.com"],
"preload": [{
type: "style",
url: "//domain.com/path/to/style.css"
},
{
type: "script",
url: "//domain.com/path/to/script.js"
},
{
type: "fetch",
url: "/domain.com/path/to/a/config.json"
},
{
type: "font",
url: "//domain.com/path/to/iconfont.eot?abc123"
},
{
type: "font",
url: "//domain.com/path/to/iconfont.eot?abc123?7ipyug#iefix"
},
{
type: "font",
url: "//domain.com/path/to/iconfont.ttf?abc123"
},
{
type: "font",
url: "//domain.com/path/to/iconfont.woff?abc123"
},
{
type: "font",
url: "//domain.com/path/to/iconfont.svg?abc123#iconfont"
}
],
"prerender": [
"//domain.com/path/to/some/page",
"//domain.com/path/to/some/other/page"
]
};
// Preconnect
for (var i = 0, l = resourceHints.preconnect.length; i < l; i++) {
linkPreconnect(resourceHints.preconnect[i]);
}
// Preload static assets
for (var i = 0, l = resourceHints.preload.length; i < l; i++) {
linkPreload(resourceHints.preload[i].type, resourceHints.preload[i].url);
}
// Once have link pages (not privacy/tos)
let ;
for (var i = 0, l = resourceHints.prerender.length; i < l; i++) {
// Use prerender if Chrome, Opera, Samsung
if (isOpera || isChrome) {
linkPrerender(resourceHints.prerender[i]);
} else {
// Otherwise use prefetch
linkPrefetch(resourceHints.prerender[i]);
}
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment