4

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.

Current Workaround

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);
})();

The Question

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
Michael Robinson
  • 29,278
  • 12
  • 104
  • 130

1 Answers1

2

Try attaching an onload callback to the iframe.

You might need to bump the src attribute incase the iframe is loaded before you attach the onload callback.

Petah
  • 45,477
  • 28
  • 157
  • 213
  • I did what you suggested in place of the `alert('rendered!');` in the code example in my question above. With this method I so far haven't noticed the ugly pop-in effect on my G+ button. Thanks! – Michael Robinson Apr 04 '12 at 22:28