Shortcut for including social JavaScript
A while ago, I noticed that a lot of the social JavaScript plugins (Facebook, Google+, Twitter buttons) use pretty much the same code. I decided this was wasteful, so I refactored the common code into a tiny snippet. Now all you need to do is add the JavaScript code below to your page inside a <script>
tag, and choose which social widgets you want to include.
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-587112-4']);
_gaq.push(['_trackPageview']);
!function(d,s){
var st=d.getElementsByTagName(s)[0],j=function(id,p){var js;if(d.getElementById(id))return;js=d.createElement(s);js.id=id;js.async=true;js.src=p;st.parentNode.insertBefore(js,st);}
setTimeout(function(){
j("twitter-wjs","//platform.twitter.com/widgets.js");
j("facebook-jssdk","//connect.facebook.net/en_GB/all.js#xfbml=1");
j("gplusone-sdk","https://apis.google.com/js/plusone.js");
}, 0);
j("ga-sdk",('https:'==d.location.protocol?'https://ssl':'http://www')+'.google-analytics.com/ga.js');
}(document,'script');
The code is fairly minified, although there is some whitespace that can be removed. It includes the following external scripts:
- Google+
- Google Analytics
Google Analytics is loaded with the page; the others wait until the DOM is ready so that their elements are definitely in place. Feel free to modify the code to add other external scripts as necessary.
Deconstructing the code
First of all, we set up some of the required Google configuration. The interesting things start with !function(d,s){
. This defines and immediately executes an anonymous function, which takes two arguments. The arguments are given at the very end: document
and 'script'
. This is done purely to save space and reduce repetition.
Next, we find the current <script>
tag and store it in st
, and create a locally-scoped function j
. This does the main work, and we’ll come back to it in a moment.
Finally we set up a 0-millisecond timeout which will execute as soon as the page has loaded. This calls the function that adds the relevant scripts to the page. We also immediately add the Google Analytics script, so we get that data as fast as possible (because it doesn’t rely on the rest of the page).
So, back to our mysterious j
function. This takes two arguments: an ID (so we can make sure the script isn’t included twice) and the URL of the script we want to include. We first check to see if an element exists in the page with the given ID; if it does, we stop immediately. Otherwise we create a <script>
element and initialise its properties: id
, async
(so it doesn’t block the rest of the page), and src
(the script URL). We then add it to the page immediately before the current <script>
tag. The browser will immediately start processing that script asynchronously, and we can carry on.
… and that’s it! I hope this proves useful, and remember; it’s not worth the extra HTTP request to fetch a script this small — it works out better to have it inline.
Leave a Reply