Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

Add Google +1 Button To Website

5.00/5 (1 vote)
26 Mar 2012CPOL2 min read 21.4K   498  
Delay load g+1 button to make web page loads faster and more responsive

Image 1

Introduction

In our previous article Add Facebook Like Button To Website, we explained the reason for using this technique.

"One notorious problem of adding social buttons, such as the Facebook Like button, to a website is that they can significantly slow down loading your web page. Though by using asynchronous load technique this problem has been solved somewhat, the page load time and responsiveness is still a big issue, especially when there are multiple social network buttons on a page...."

Get Your g+1 Button

If you have not done so, following this link to get your own Google +1 button. The source code for Voicent's +1 button is shown below:

JavaScript
<g:plusone size="medium" annotation="inline" href="..."></g:plusone>

...

When you put this code in your web page, it will show a Google Plus One button with the counter on the right.

Delay Load the g+1 Button

In order to render the Google +1 button, your browser has to make a trip to the Google website. The embedded javascript code needs to query how many people has +1 the item, and who is the current google user, and then display the details like the total pluses on the right.

Though the Google +1 button has asynchronous support, it is still interfere with the responsiveness of the page. We go a step further by delaying the load until a mouse is moved over the button.

In the place of the g:plusone tag, replace it with a simple img tag with onMouseOver defined as follows:

C++
<div id="plusone-div">
  <img sec="/images/gplus-button.png" onMouseOver="renderPlusone();">
</div>

The renderPlusone() Javascript is shown below. The "explicit" value for "parsetags" informs the plusone.js to render the button only render() is called.

JavaScript
<script type="text/javascript" src="https://apis.google.com/js/plusone.js</a />">
  {"parsetags": "explicit"}
</script>
<script type="text/javascript">
  function renderPlusone() {
    gapi.plusone.render("plusone-div", {"size": "medium", "annotation": "inline" });
  }
</script>

Since we cannot add the Javascript on this codeproject page, we'll not be able to show you how the button really behaves. But you can go to our email marketing software promotion page and give it a try.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)