On Render Callback For G+ Button

Posted by Michael Robinson on Stack Overflow See other posts from Stack Overflow or by Michael Robinson
Published on 2012-04-03T02:46:49Z Indexed on 2012/04/03 23:28 UTC
Read the original article Hit count: 259

How might I go about performing an action only when a G+ button has finished rendering?

Facebook allows one to do this using the following:

FB.XFBML.parse(document, function() {
    alert('rendering done');
});

I've perused Google's documentation, but didn't see anything helpful.

Currently my workaround is to monitor the G+ element until certain elements have been added, then perform my action:

(function() {
    var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js';

    po.onload = function() {
        var awaitRender = function(element) {
            if (element.firstChild &&
                element.firstChild.firstChild &&
                element.firstChild.firstChild.tagName.toUpperCase() === 'IFRAME') {
                alert('rendered!');
            } else {
                window.setTimeout(function() { awaitRender(element) }, 100);
            }
        };

        var buttons = document.getElementsByClassName('googleplus-button');
        for(var i = 0; i < buttons.length; i++) {
            awaitRender(buttons[i]);
        }
    }
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(po, s);
})();

I'd like to know please, if there is either:

  • A correct way one should do this for G+ buttons
  • A better implementation that what I've hacked together above

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about google-plus