Tutorial: Load the Google +1 button asynchronously

Introduction

In our previous article, we explained how to produce a valid Google +1 button. That’s nice, but you will probably notice that the button is rendered only after your website is completely loaded. This approach is problematic, especially regarding the fact that during the loading of the script, your page appears to be frozen. And let’s say it, this button is slow!

Fortunately, there are some solutions to circumvent this problem. It is possible to load scripts asynchronously so that it does not block your webpage rendering, and the script will be ready to use as soon as it is loaded.

We will use a technique similar to the one used by Google Analytics, with the difference that we had to modify it a little so that it is still possible to customize the button while speeding it up a little.

Ready? Let’s go !

Implementation

First add your DIV tag:

Nothing complicated. Note that you must not add the “g-plusone” class to this DIV.

Then anywhere after the DIV tag, add the following code:

 

Explanation

Let’s explain this code a little so that you can understand it faster:

  1. The function “getElementByIdUniversal()” returns the element corresponding to the specified “id” parameter. It is similar to the “getElementById” function but it also work with old versions of Internet Explorer.
  2. The function “plusoneready()” is a callback that will be called once the Google +1 Javascript file is loaded.
  3. Then we begin a self-running anonymous function.
  4. We create a SCRIPT element of type ‘text/javascript’.
  5. We take care to set the “async” member to “true” so that the script will load asynchronously.
  6. We set the “src” member to “https://apis.google.com/js/plusone.js”. Note that you should use “https” and not “http” if you want to avoid the cost of a useless redirection…
  7. We set the “onload” member to be our callback function.
  8. For IE 6 and 7, we have to use the “onreadystatechange” member to be able to call our callback.
  9. We find our DIV element using its ID
  10. We add our SCRIPT tag just before our DIV
  11. End of the anonymous function

 

Conclusion

And that’s it! Your Google +1 button will now load asynchronously and should not stop other elements from rendering.

If you have some suggestions to improve the previous code or found any issue, do not hesitate to give your feedback in the comments!

Happy coding.