Speed arrow Defer popular javascript

clock and various logos

This article will describe how to defer images, videos, Twitter / Facebook / G+ buttons, and Analytics. Using the same method you can defer just about anything else too.

Deferring of javascript can be an important step to faster webpages. I have written extensively about deferring images, videos, and how to defer javascript in general but the most common question I receive is...

"How do I defer more than one javascript?"

An example of this might be that you have figured out how to defer videos maybe, but also want to defer Analytics and/or social buttons too.

A practical guide to deferring multiple javascripts

A regular webpage will load the javascript of many things like Analytics, social buttons, badges, video scripts and widgets slowing down the initial view of that web page considerably. Often this adds seconds to the page load. It need not.

Often the javascript that is loading is not needed for the initial page load because it does not have anything to do with the above the fold content.

A great example of this is Google Analytics. Since analytics does not need to load to display the above the fold content of our webpages, why do we always make it load before the user sees the page? Another common culprit is social buttons or badges. If they are not displayed above the fold, there is no reason to delay your users from seeing your page by loading all their dependencies.

Deferring multiple things

To defer multiple things until after the initial page load requires two things.

This should not scare you. It is less complicated than it sounds, especially if you are already deferring an external javascript file.

Let's explore each of those in order starting with the javascript defer.

How to defer javascript

To defer javascript completely out of the page load event (to make our pages load faster) we need to add a bit of javascript at the end of the page. I will do a quick summary of that here in this article but the in depth guide to the method is here.

This code should be placed in your HTML just before the </body> tag (near the bottom of your HTML file). I highlighted the name of the external JS file.

<script type="text/javascript">
function downloadJSAtOnload() {
var element = document.createElement("script");
element.src = "defer.js";
document.body.appendChild(element);
}
if (window.addEventListener)
window.addEventListener("load", downloadJSAtOnload, false);
else if (window.attachEvent)
window.attachEvent("onload", downloadJSAtOnload);
else window.onload = downloadJSAtOnload;
</script>

What does this do?

This code says wait for the entire document to load, then load the external file "defer.js".

Specific instructions

  1. Copy above code.
  2. Paste code in your HTML just before the </body> tag (near the bottom of your HTML file).
  3. Change the "defer.js" to the name of your external JS file.
  4. Ensure the path to your file is correct. Example: if you just put "defer.js", then the file "defer.js" must be in the same folder as your HTML file.

Okay once you have that you are now able to defer just about anything that your webpage loads, let's look at what we need to put in that file now.

What to put in the external file

Let's start out with a common one, Google Analytics. If you want to defer Google Analytics you would place your Analytics code snippet in the external file that we called "defer.js". Here is an example code snippet...

(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-XXXXXXXX-1', 'example.com');
ga('send', 'pageview');

Obviously your analytic code snippet will be different, but the the point is you just copy and paste your snippet into the file "defer.js" and save it.

The next time you load or refresh your page you will notice that you have deferred Google analytics out of your page load time, making your page load a little bit faster. This means that your webpage content loads, and then as soon as it loads, the Google analytics javascript fires and you have both your analytics and happy users.

That is great but the point of this article is how to defer many things, not just one. Let's discuss that.

Deferring multiple javascripts

Thus far we have deferred Google Analytics, but let's say we also want to defer our Google plus button or badge. Now what?

What we must now do is known as combining javascripts, or what it more commonly known as is "copy and paste".

Let's look at at our defer.js file. It currently has our Google Analytics code snippet in it and looks like this...

(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-XXXXXXXX-1', 'example.com');
ga('send', 'pageview');

Now we want to defer our Google plus button or badge. We would now copy and paste the G+ code snippet into the the file as well making it look like this..

//Google plus button / badge
(function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/platform.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

//Google analytics code
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-XXXXXXXX-1', 'example.com');
ga('send', 'pageview');

We have now combined javascript. It really is just copying and pasting :) I will now list out some of the scripts that you can add to your defer.js file.

These code snippets can be used by copying and pasting into your defer.js file. If you want to use one of them or all of them or some combination in between, you just copy and paste one, hit enter to leave a space, then copy and paste another.

Deferring Google plus buttons and badges

This code will work for just about any button or badge for Google plus...

(function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/platform.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

Notes: When you get a code snippet for a Google plus badge or button it will say something like "<!-- Place this tag in your head or just before your close body tag.>" and "<!-- Place this tag where you want the share button to render. -->". When you use the above code to defer, you are in essence replacing the part of the code that says "<!-- Place this tag in your head or just before your close body tag.>". You can remove that part of the code snippet from your page (or it will still load).

Deferring Twitter buttons

Deferring a Twitter button, much like the Google plus button requires placing part of the code snippet in our defer.js file.

!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');

Notes: When you go to twitter and get the code for a button it looks something like this...

<a href="https://twitter.com/share" class="twitter-share-button" data-via="yummyman">Tweet</a>

<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script>

We are deferring the part of the code that has script tags around it, which means you should not have the part with script tags anywhere on your page, or you will just be double loading the javascript.

Deferring Facebook buttons

Deferring a Facebook button, much like the Google plus / Twitter buttons requires placing part of the code snippet in our defer.js file.

(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.0";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

Notes: When you go to Facebook and get the code for a button it looks something like this...

<div id="fb-root"></div>

<script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.0"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));</script>

<div class="fb-like" data-href="http://www.feedthebot.com/" data-layout="button_count" data-action="like" data-show-faces="false" data-share="false"></div>

We are deferring the part of the code that has script tags around it, which means you should not have the part with script tags anywhere on your page, or you will just be double loading the javascript. You also do not need the part that says "<div id="fb-root"></div>" either when you use this method.

Deferring images

Deferring images is explained in depth in my article here. This is the code snippet from that page.

var imgDefer = document.getElementsByTagName('img'); for (var i=0; i<imgDefer.length; i++) { if(imgDefer[i].getAttribute('data-src')) { imgDefer[i].setAttribute('src',imgDefer[i].getAttribute('data-src')); } }

Notes: This script will defer any image that has a "data-src" in it as explained in the defer images article.

Deferring videos

Deferring videos from Youtube, Vimeo, etc. is explained in depth in my article here. This is the code snippet from that page.

var vidDefer = document.getElementsByTagName('iframe');
for (var i=0; i<vidDefer.length; i++) {
if(vidDefer[i].getAttribute('data-src')) {
vidDefer[i].setAttribute('src',vidDefer[i].getAttribute('data-src'));
}}

Notes: This script will defer any video that has a "data-src" in it as explained in the defer video article.

Deferring Google Analytics

To defer Analytics, add your code snippet provided from Google into defer.js, example...

(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-XXXXXXXX-1', 'example.com');
ga('send', 'pageview');

Notes: I tend to keep my analytics code snippet as the last thing in the file.

Problems you may encounter

Each of the above methods work. If one of them is not working for you, make sure you are reading the notes included in each section.

None of the examples above have any dependencies (this means they do not rely on other files to work).

Some of your javascript will have dependencies so if you try to defer other things than the example above, you should be aware of what dependencies your file have.

A common example is jQuery. You may have javascript that uses jQuery or some other library, if you do, you can still use this method but you have to make sure the order of scripts is right. If you have a javascript that uses jQuery, just make sure jQuery is loaded first.

Deferring jQuery

Deferring jQuery is indeed possible, but I do not recommend it per se. If you want to defer jQuery just copy and paste it as the first thing in the defer.js file, but be warned, it is really huge and in general I do not do it like that.


Patrick Sextonby Patrick Sexton

Deferring multiple popular javascripts