Defer Loading JavaScript Files to Improve Page Load Time

by

Almost all sites and blogs have various social sharing buttons like ‘Tweet’, ‘Like’ or ‘+1’ to spread there writings. To render these buttons we need to import some JavaScript source files from there respective locations. The task of copy-paste of the button code is simple and does not require any expertise. But there is a great downside of this.

In order to load and display a page, the browser first must parse the contents of all <script> tags, which adds additional time to the page load. Thus, we should avoid loading of any resources which are not needed immediately after the page loads. This short and sweet little tutorial will explain you how to reduce the initial load time of your page by deferring parsing of unneeded JavaScript until it needs to be executed.

How to use Deferring Technique

[Re-written this section to make it very very simple after getting feedback from many newbies.]
[Modified 3rd September, 2012]

Do a fresh start, remove everything you have inserted earlier to integrate social buttons.

Part 1

Create a new JavaScript file and put the JS import section of all social media buttons in that. Here I am creating def-func.js. The content of the file will be like this.

//For Google +1
var element = document.createElement("script");
element.src = "https://apis.google.com/js/plusone.js";
document.body.appendChild(element);
gapi.plus.go();

//For Twitter
var element = document.createElement("script");
element.src = "//platform.twitter.com/widgets.js";
document.body.appendChild(element);

//For Facebook
(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/all.js";
	fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

Here I have only included contents for for Google+, Twitter and Facebook. But do include imports for other networks if you are going to use them on your site. Like Digg, Pinterest, StumbleUpon, LinkedIn etc. Host this file in home directory only.

Part 2

Now, we insert a JavaScript event listener in the head of the HTML containing document which will force the def-func.js file to load after the onload event. Here is the code, simply copy and paste this in the head section.

<script type="text/javascript">
function LoadJavaScript() {
	var element = document.createElement("script");
	element.src = "def-func.js";
	document.body.appendChild(element);
}

if (window.addEventListener)
	window.addEventListener("load", LoadJavaScript, false);
else if (window.attachEvent)
	window.attachEvent("onload", LoadJavaScript);
else window.onload = LoadJavaScript;
</script>

You can do this by any of the usual scripting means, but here I have used scripted DOM element.

Part 3

Now insert individual code for rendering the buttons at the place you want them. For example to render those three buttons, place this part of code at that point.

//Google+
<g:plusone size="medium" href="http://www.site_url.com"></g:plusone>

//Twitter
<a href="https://twitter.com/share" class="twitter-share-button" data-url="http://www.site_url.com" data-count="horizontal" data-via="yoursite">Tweet</a>

//Facebook
<fb:like href="http://www.site_url.com" layout="button_count" send="false" show_faces="false" font="tahoma"></fb:like>

So you have seen that the peice of code they provide is broken in two parts. First part in included in step 1, and the second part is included in step 3. In the similar fashion you can add the codes for other buttons.

To test if it is working, reload the page in Chrome with developer console and observe timings. Take reference of this snapshot.

There are services which automatically take care of these optimizations and reduce the page loading time to just a few milliseconds by optimizing all assets such as CSS, JS, Images, Fonts etc.

That’s all for this post. If you face any problem in doing this, do post in comments. I’ll try to reply.