How to Load Social Widgets Conditionally to Improve your Site's Performance
Social Sharing is now tightly integrated into all mobile OS platforms. That means if someone is viewing a web page on an Android phone, or inside the mobile Safari browser of an iPhone, they can share that web page on Twitter and Facebook using the system-wide sharing menu without having to rely on bookmarklets or those tiny social sharing widgets.
These “tweet” and “like” buttons add several extra kilobytes to your web pages and if mobile users are less likely to use them, you may as well consider removing the social buttons completely when your website is accessed from a mobile phone. This reduces clutter and also improves the page speed score which is now a factor in Google search rankings.
For a quick demo, open social-widgets.html in your desktop browser and then on a mobile device. The desktop view will load the social widgets but not the mobile device.
The technique is simple. We calculate the width of the user’s screen /browser and if the width exceeds a particular value (say 480 pixels), we load the associated social widgets.
To implement conditional loading on your blog /website, first add all the necessary social widgets to your blog using the usual procedure. For instance, you can visit facebook.com to generate code for the Like button while dev.twitter.com will provides codes the Tweet and Follow widgets of Twitter.
<script> tags - and add everything else to your website template. Then copy-paste the following snippet before the closing
</body> tag of your website template.
I have implemented a variation of the above code on my site as well. There’s a Facebook Like box in the right sidebar but it won’t load if you open this site on a mobile device.
Also see: Making Google Ads Responsive
Google Developer Expert, Google Cloud Champion
Amit Agarwal is a Google Developer Expert in Google Workspace and Google Apps Script. He holds an engineering degree in Computer Science (I.I.T.) and is the first professional blogger in India.