Skip to content

Instantly share code, notes, and snippets.

@19h
Last active December 30, 2018 04:17
Show Gist options
  • Save 19h/2da1085913b94add85315e08959bafa6 to your computer and use it in GitHub Desktop.
Save 19h/2da1085913b94add85315e08959bafa6 to your computer and use it in GitHub Desktop.
preconnect hooker for external links
// 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