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 !
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
Let’s explain this code a little so that you can understand it faster:
- 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.
- Then we begin a self-running anonymous function.
- We take care to set the “async” member to “true” so that the script will load asynchronously.
- 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…
- We set the “onload” member to be our callback function.
- For IE 6 and 7, we have to use the “onreadystatechange” member to be able to call our callback.
- We find our DIV element using its ID
- We add our SCRIPT tag just before our DIV
- End of the anonymous function
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!