Search code examples
javascripthtmlfacebook-likegoogle-plussharethis

Addthis/Sharethis VS adding each button "manually"


i would like to add an fb-like, google+1, tweet-button etc to my new page (when displaying a certain post). I know that for example addthis offers this by default. But the downside is that you get a somewhat large javascript file that ocasionally throws some errors. So my question is: Which option and why do you guys usually go for in similar scenarios. Thanks


Solution

  • The inclusion via addthis is not my preferred way to include social buttons. In fact as you noticed, sometimes some errors are thrown and if the addthis library fails (e.g. javascript error, server timeout...) all buttons could fail, since they depend by a unique library. Beside, for a simple matter of performance, addthis is a script who loads other scripts (it's 33kb gzipped) so it can be avoided and I can take full control of social buttons inclusion.

    I prefer load asynchronously all the needed libraries and inject the necessary markup only if I really need them, like this

    $(document).ready(function() {
    
        if (('.socialshare').length) {
    
           /* twitter button */      
           $('<a href="https://twitter.com/share" class="twitter-share-button">Tweet</a>').appendTo($('.socialshare'));
           loadscript('//platform.twitter.com/widgets.js', 'twitter')
    
           /* Google +1 button */      
           $('<div class="g-plusone" data-size="medium" data-annotation="bubble"   data-expandTo="top"></div>').appendTo($('.socialshare'));
           loadscript('https://apis.google.com/js/plusone.js', 'google-plusone');
        }
    
    })
    

    (for the sake of performance, cache a reference to .socialshare) loadscript is a simple script loader function like this

    function loadscript(url, id) {
        var js, fjs = document.getElementsByTagName('script')[0];
        if (document.getElementById(id)) { return; }
        js = document.createElement('script'); 
        js.id = id;
        js.charset = "utf-8";
        js.src = url;
        fjs.parentNode.insertBefore(js, fjs);
    };
    

    basically if my template contains the element with social button (the .socialshare element) I inject the script element with an id (so that I'm sure no other script can inject them twice)