Better Embedding Code for Google +1 Buttons

Tuesday, June 7, 2011
Google wants to see a +1 button on each Web page, but many people hate embedding widgets and buttons because they clutter pages and add hundreds of milliseconds to the page loading time.

Google is obsessed with speed and performance, but it didn't do a good job at optimizing the code for embedding +1 buttons. As Aaron Peters explains, Google's code blocks page loading if you place it inside the <head> tag, so it's better to place it before you close the <body> tag. An even better idea is to load the Google +1 script in a non-blocking way, just like Google did with Google Analytics, AdSense and Google Related Links.

Aaron also noticed that the JavaScript code is not minified, browsers can only cache the JavaScript file for 6 minutes and there's a mistake in the code from this page: "http" should be replaced with "https" to avoid an unnecessary redirect.

Here's a better embedding code suggested by Aaron:

<!-- Place this tag just before your close body tag -->
<script>
(function(d, t) {
var g = d.createElement(t),
s = d.getElementsByTagName(t)[0];
g.async = true;
g.src = 'https://apis.google.com/js/plusone.js';
s.parentNode.insertBefore(g, s);
})(document, 'script');
</script>

<!-- Place this tag where you want the +1 button to render -->
<g:plusone></g:plusone>

Apparently, the code doesn't work in Blogger by default. There's a workaround, but you shouldn't use it if you aren't familiar with HTML and editing Blogger's template. Basically you can replace <b:include data='blog' name='all-head-content'/> with the code generated by Blogger ("view source" is your friend), then delete: <meta content='blogger' name='generator'/>.

As Google explains, "most browsers will load the code in parallel with other scripts on the page, thus reducing the web page load time".

0 comments:

Post a Comment