Performance Optimization: How to Load your javascript faster!
Javascript 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
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.
- YUI Compressor (my favorite, used by jQuery team), beginners guide, second guide and official site
- Dean Edwards Packer
- JSMin
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 librarieshttp://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js
– Microsoft’s CDNhttp://code.jquery.com/jquery-1.4.2.min.js
– Edgecast (mt)
Load your javascript at the end of page
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 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
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
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.
- Login om te reageren