UNPKG

1.61 kBJavaScriptView Raw
1// tachyon.js 2.0.1 - @weebney - MIT License
2const bodyDataValues = document.body.dataset;
3const whitelistEnabled = 'tachyonWhitelist' in bodyDataValues;
4const sameOriginOnly = 'tachyonSameOrigin' in bodyDataValues;
5const timerDuration = bodyDataValues.tachyonTimer || 50;
6let lastTouchedAnchor = null;
7
8function toggleLinkTag() {
9 lastTouchedAnchor = lastTouchedAnchor ? null : this;
10 const linkTagId = 'tachyon';
11 const linkTag = document.getElementById(linkTagId);
12 if (linkTag) {
13 linkTag.remove();
14 } else {
15 setTimeout(() => {
16 if (lastTouchedAnchor === this) {
17 const newLinkElement = document.createElement('link');
18 newLinkElement.id = linkTagId;
19 newLinkElement.href = this.href;
20 newLinkElement.rel = 'prerender';
21 document.head.appendChild(newLinkElement);
22 }
23 }, timerDuration);
24 }
25}
26
27function initializeListeners(node) {
28 if (node.dataset) {
29 const listed = 'tachyon' in node.dataset;
30 if ((node.tagName === 'A' && node.href) && (listed === whitelistEnabled || sameOriginOnly)
31 && (!sameOriginOnly || (listed || (node.origin === window.location.origin)))) {
32 ['mouseover', 'mouseout', 'touchstart', 'touchend'].forEach((eventName) => node.addEventListener(eventName, toggleLinkTag, { passive: true }));
33 }
34 }
35}
36
37const mutationObserver = new MutationObserver((mutationRecordArray) => mutationRecordArray
38 .forEach((record) => record.addedNodes.forEach(initializeListeners)));
39
40mutationObserver.observe(document.body, { childList: true, subtree: true });
41
42document.querySelectorAll('a').forEach(initializeListeners);