Last active
May 21, 2024 19:32
-
-
Save colepeters/64b76649c25f9d7070e4343d21ebfe5f to your computer and use it in GitHub Desktop.
Example of a custom element to prefetch a link's `href`
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
<prefetched-link href="https://prefetch-this-href.example.org"> | |
This link's href is prefetched if the user is on a fast network | |
</prefetched-link> |
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
export default function PrefetchedLink({ html, state }) { | |
const href = state.attrs.href | |
return html` | |
<a href="${href}"> | |
<slot></slot> | |
</a> | |
<script type="module"> | |
class PrefetchedLink extends HTMLElement { | |
constructor() { | |
super() | |
this.anchor = this.querySelector('a') | |
this.href = this.anchor.getAttribute('href') | |
} | |
connectedCallback() { | |
if (window.navigator.connection.effectiveType === '4g') { | |
//generate link prefetch tag | |
const linkTag = document.createElement('link') | |
linkTag.rel = 'prefetch' | |
linkTag.href = this.href | |
linkTag.as = 'document' | |
//inject tag in the head of the document | |
document.head.appendChild(linkTag) | |
} | |
} | |
} | |
window.customElements.define('prefetched-link', PrefetchedLink) | |
</script> | |
` | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment