Pete Freitag Pete Freitag

Replacing Twitter Share / Follow Widget Buttons with CSS

Updated: July 07, 2021
web

While looking at the PageSpeed Insights for my blog I noticed that the Twitter widgets I was using to display a twitter follow button and a tweet / share button were causing some page speed issues. Specifically the TBT (Total Blocking Time), LCB (Largest Contentful Paint) saw an impact. Overall it was taking about 151 KiB and blocking the main thread for 56ms.

Here's an example of what I was using:

<a href="https://twitter.com/pfreitag" class="twitter-follow-button" data-show-count="true" data-size="large">Follow @pfreitag</a>
<script async src="https://platform.twitter.com/widgets.js"></script>

That loads the following button:

Taking a look at this script, it replaces the button with an iframe, it's just quite simply overkill for what it does.

Replacing the Twitter button with pure CSS

It should be easy enough to replace this button with a pure css implementation. First, we should replace https://twitter.com/pfreitag with a twitter intent to follow url, for example: https://twitter.com/intent/follow?screen_name=pfreitag. We can also get rid of data-show-count="true" data-size="large" in the link. One thing our new solution won't have is that nice follower count, but I can live without it. It would be possible to add that back in again, perhaps using a hard coded count to keep it efficient.

Finally here's the css we are using to make the button look similar to the twitter follow button:

.twitter-follow-button, .twitter-follow-button:visited {
    background-color: #1b95e0;
    color: #fff;
    border-radius: 4px;
    height: 28px;
    font-weight: 500;
    font-size: 13px;
    line-height: 26px;
    padding: 8px 8px 8px 30px;
    text-decoration: none;
    background-image: url('/images/twitter.png');
    background-repeat: no-repeat;
    background-size: 16px 13px;
    background-position: 8px 10px;
}
.twitter-follow-button:hover {
    background-color: #0c7abf;
}

One thing you'll note is that we are using an image for the twitter logo, if you want to make the button even more efficient you can just use something like this:

.twitter-follow-button, .twitter-follow-button:visited {
    background-color: #1b95e0;
    color: #fff;
    border-radius: 4px;
    height: 28px;
    font-weight: 500;
    font-size: 13px;
    line-height: 26px;
    padding: 8px;
    text-decoration: none;
}
.twitter-follow-button:hover {
    background-color: #0c7abf;
}

Another good reason to remove the twitter JavaScript is that it also makes the Content-Security-Policy for twitter buttons much easier to implement.

To see an example of the pure CSS button take a look below the end of this entry.


Like this? Follow me ↯

Replacing Twitter Share / Follow Widget Buttons with CSS was first published on July 07, 2021.


Post a Comment