Share buttons without JavaScript
First appeared on mobifreaks.com · Updated
Whenever I checked a page's load time in 2012, the slowest parts were the Facebook Like, Twitter Tweet and Google +1 buttons. Each loaded its own JavaScript, and often tracking along with it. So I went looking for share buttons with no JavaScript and no load time. They are just links.
The idea still holds, and it matters more now: plain links load nothing from third parties and don't track your readers. The URLs have changed, though, so here is the updated set. The original post was called "Facebook, Twitter and Google plus share buttons without JavaScript".
<a href="https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fexample.com%2Fpost"
target="_blank" rel="noopener">Share on Facebook</a>
X (Twitter)
My 2012 link used twitter.com/home?status=, an old undocumented address. The documented share link is the Post web intent, which takes the URL and the text separately:
<a href="https://x.com/intent/tweet?url=https%3A%2F%2Fexample.com%2Fpost&text=Post%20title"
target="_blank" rel="noopener">Share on X</a>
<a href="https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fexample.com%2Fpost"
target="_blank" rel="noopener">Share on LinkedIn</a>
Google Plus
Google shut down Google+ for consumers in April 2019, so that button can go.
Notes
- URL-encode the page address (
encodeURIComponent()in JavaScript,rawurlencode()in PHP). My 2012 WordPress versions droppedthe_permalink()straight in, which breaks on URLs with&in them. rel="noopener"stops the new tab from controlling your page. Current browsers do this by default fortarget="_blank", but it costs nothing to be explicit.- Label the links clearly. "Share on X" is better than an icon alone; if you use icons, add the text for screen readers.
One button for every app: the Web Share API
On phones, a single button can open the system share sheet, which lists every app the reader has: WhatsApp, Messages, email, Slack and the rest. It needs a few lines of JavaScript, so keep the plain links as a fallback:
<button type="button" class="share" hidden>Share</button>
<script>
const btn = document.querySelector('.share');
if (navigator.share) {
btn.hidden = false;
btn.addEventListener('click', () => {
navigator.share({ title: document.title, url: location.href }).catch(() => {});
});
}
</script>
The button only appears in browsers that support sharing, and .catch() quietly handles the reader closing the share sheet.