Last active
December 30, 2018 04:17
-
-
Save 19h/2da1085913b94add85315e08959bafa6 to your computer and use it in GitHub Desktop.
preconnect hooker for external links
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://gist.github.com/KenanSulayman/2da1085913b94add85315e08959bafa6 | |
;(() => { | |
const runner = () => { | |
const processed: string[] = []; | |
const preconn = (type: string, url: string) => { | |
if (~processed.indexOf(url)) { | |
return; | |
} | |
processed.push(url); | |
const hint = document.createElement('link'); | |
hint.rel = type; | |
hint.as = 'fetch'; | |
hint.href = url; | |
document.head.appendChild(hint); | |
}; | |
[].slice.call(document.body.getElementsByTagName('a')) | |
.forEach((a: HTMLAnchorElement) => { | |
const isExternalLink = !/psychonautwiki\.org/.test(a.href); | |
a.addEventListener('mouseenter', e => { | |
if (isExternalLink) { | |
const match = /(https?:\/\/.*?)\//.exec(a.href)[1]; | |
preconn('preconnect', match); | |
return; | |
} | |
preconn('preload', a.href); | |
preconn('prerender', a.href); | |
}); | |
if (!isExternalLink) { | |
return; | |
} | |
a.addEventListener('mousedown', e => { | |
preconn('prerender', a.href); | |
}); | |
}) | |
}; | |
document.readyState !== 'loading' ? runner() : document.addEventListener('DOMContentLoaded', runner); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment