Performance Optimization: How to Load your javascript faster!

Load your javascript fasterJavascript is now extremely important. Some sites use javascript for a tiny enchantments, many of today’s webapps are depending on it, some of them are even totally written in js. In this article I’ll point out some important rules, how to use your javascript, which tools to use and what benefits you’ll gain from it.

Keep your code at minimum

Keep your code at minimum

Don’t rely on javascript. Don’t duplicate your scripts. Treat it like a candy-tool to make things more pretty. Don’t bloat your site with s**t-loads of javascript. Use it only when necessary. Only when it really improves user experience.

Minimize DOM access

Accessing DOM elements with JavaScript is easy, code is more readable, but it’s slow. Here are some tips: Limit your layout fixing with javascript, cache references to accessed elements. Sometimes when your site is depending so much on DOM modifications you should consider limiting your markup. It’s a good reason to switch to HTML5 and leave those old XHTML, HTML4 behind. You can check the number of your DOM elements by typing in Firebug’s console: document.getElementsByTagName('*').length

Compress your code

The most efficient way to serve compressed JavaScript is to first run your code through a JavaScript compressor that shrinks variable and argument names, and then serve the resulting code using gzip compression.

Well, I don’t compress my main.js, but check if you have any jQuery plugins that are not compressed, do it (remember to keep author’s notes). Below I listed some options for compression.

GZip Compression: Idea behind this is to reduce time of transferring data between browser and server. When it’s done you get your file with Accept-Encoding: gzip,deflate header. It has some disadvantages though. It takes: CPU on both server-side and client side (to compress and uncompress) and disc space.

Avoid eval(): While sometimes it may bring some time efficiency, it’s definitely wrong practice. It makes your code look more dirty and it crashes out most of the compressors.

Tool to speed up javascript loading – Lab.js

There are many awesome tools that could speed up your javascript loading time. One is worth mentioning — Lab.js.

With LAB.js (Loading And Blocking JavaScript) you can load your javascript files in parallel, speeding up the total loading process. What is more you can also set up certain order for scripts to be loaded, so no dependencies are broken. Also, the developer declares a 2x speed improvement on his site.

Using proper CDN

Many webpages now use CDN (Content delivery network). It improves your caching, because everybody can use it. It can also save you some bandwidth. You can easy ping or firebug those servers to check from where you get data faster. Choose CDN by matching your readers localization. Remember to use public repositories when it’s possible.

Some CDN options for jQuery:

  • http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js – Google Ajax, information about more libraries
  • http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js – Microsoft’s CDN
  • http://code.jquery.com/jquery-1.4.2.min.js – Edgecast (mt)

Load your javascript at the end of page

Load your javascript at the end

Very good practice if you care about user and him/her not leaving your page because of slow internet connection. Usability and user at first, javascript at the end. This may be painful, but you should be prepared for users with disabled javascript. You may put some javascript to be loaded in head section, but only if it’s loading asynchronously.

Load tracking asynchronously

This one is very important. Most of us are using Google Analytics for statistics. It’s good. Now look where you put your tracking code. Is it in head section? Is it using document.write? Then you should blame yourself for not using asynchronous tracking code for Google Analytics.

This is what asynchronous tracking code for Google Analytics looks like. We must acknowledge that it uses DOM instead of document.write, which may be better for you. It detects some of the events before page load which is very important. Now think of all the users closing your page before it even loaded. The cure of missing page views has been found.


	var _gaq = _gaq || [];
	_gaq.push(['_setAccount', 'UA-XXXXXXX-XX']);
	_gaq.push(['_trackPageview']);

	(function() {
		var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
		ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
		var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
	})();

Don’t using GA? It’s not a problem, most of today’s analytics providers will allow you to use asynchronous tracking.

Ajax Optimization

Ajax Optimization

Ajax request have great impact on your site’s performance. Below I pointed some tips about ajax optimization.

Cache your ajax

Look at your code. Is your ajax cacheable? Well, it depends on data, but mostly your ajax requests should be cacheable. In jQuery your requests are cached by default, not including script and jsonp dataType.

Use GET for Ajax Requests

POST type requests takes two TCP packets to send (headers sent first, data next). GET type request takes only one packet to send (which may depend on your amount of cookies). So while your URL length is less than 2K and you want to request some data use GET.

Use ySlow

Use Free ySlow Tool

It’s both simple and extremely powerful when it comes to performance. It grades your website and shows you what you need to correct, what should be taken care of.

Bonus: Pack your javascript into PNG File

jQuery and Prototype Packed into one image

Imagine adding your JS and CSS to the end of an image and cropping it in CSS to have all the info you need in an app in a single HTTP request.

I have recently found this. What is basically does it packs up your javascript/css data into PNG file. After that you can unpack it by using the canvas API’s getImageData(). What is more it’s very efficient. You can gain about 35% compression without minifying your data. Lossless compression! I must point out that for larger scripts you can feel “some” load time while image is pointed to canvas and pixels are read.

For more information about this one check out this article from 2008.

Final Thoughts

Hope you guys liked this article. If yes, remember to share it and to say hello to me on twitter. Stay in tune for some further posts about serious performance optimization.

przemek

I'm html5 & css3 enthusiast. I also specialize in back-end programming (oo PHP, MySQL). When not coding, amateur musician and writer. Currently freelancer at purplebreak.com. My twitter profile @przemek

15 Smart Tools To Help You Build Your Freelance Business

Discover the awesome tools we use in making our clients comfortable and happy in learning new things every day.

Download Now

Comments

  1. Mark says

    I didn’t realise how slow DOM searches were until I benchmarked it a while back, totally changed my approach towards an application I was about to write. As for packing into a PNG, who would have thought!

  2. Nick says

    Very interesting post here. Certainly some tips here I will give a shot.

    I agree with NeWeb, doing a lot of the smaller things will help reap the benefits.

  3. Camry says

    It would’ve been great if the hosting company bundled the CDN options along with their regular packages or as an add-on. It would take a big load off. Unfortunately, with many web-hosts, that doesn’t happen. Which means webmasters continue to burn the midnight oil.

  4. Kami says

    Performance optimization techniques are good as long as they work on most platforms. But there are some (IE6, anyone?) exceptions that need extra effort.

    The ‘Javascript into PNG File’ technique sounds pretty interesting. I never thought something like that could be done. Do you know if this has been tested across various browser platforms?

  5. Michael says

    The best Performance Optimization is to get rid of the javascript ;-)

    Thanks for the tips.

  6. says

    Nice tips but not sure if gzip compression has to be done manually. Some application servers zip the js files while sending to browser. I tried doing manually and it does not work.

  7. says

    Wow, this’s a first time I heard about “Pack javascript into PNG File”, since 2008, but do you ever try this way? Is it useful or compatible with Jquery?

  8. Ricky says

    Well thanks for some informative tips specially last one but i think post should be bit more descriptive. BTW have a good day :-)

  9. Richard says

    Interesting post with a few tips I haven’t tried yet.

    Doing a few basic things will go a long way, just like SEO, a lot of the time it is about doing a lot of little things to get the overall benefit.

  10. says

    Good article. You forgot Google Closure for minifying. I have it automatically minifying my scripts every time I alter a script so I don’t even have to worry about minifying… it just happens.

    Thanks!

  11. says

    An addition to the CDN’s is using a virtual CDN by using other domains or even subdomains.

    For example you have your website at http://www.example.com, the javascript is at js.example.com and images at img.example.com. The browser will treat this as 3 different sites, so you’ve got the benefit of loading with 3 different threads.

    Also, the PNG compression technique is incredible, will try it out!