1 |
|
2 | const bodyDataValues = document.body.dataset;
|
3 | const whitelistEnabled = 'tachyonWhitelist' in bodyDataValues;
|
4 | const sameOriginOnly = 'tachyonSameOrigin' in bodyDataValues;
|
5 | const timerDuration = bodyDataValues.tachyonTimer || 50;
|
6 | let lastTouchedAnchor = null;
|
7 |
|
8 | function 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 |
|
27 | function 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 |
|
37 | const mutationObserver = new MutationObserver((mutationRecordArray) => mutationRecordArray
|
38 | .forEach((record) => record.addedNodes.forEach(initializeListeners)));
|
39 |
|
40 | mutationObserver.observe(document.body, { childList: true, subtree: true });
|
41 |
|
42 | document.querySelectorAll('a').forEach(initializeListeners);
|