Performance Optimization: How to Load your javascript faster!

Posted in Web Design4 years ago • Written by 18 Comments

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.

2 Written ArticlesWebsite

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

18 Comments Best Comments First
  • Jacob Seidelin

    Wednesday, September 1st, 2010 14:23

    1

    Please note that the PNG thing is just a stupid trick and should not be used in any serious project in the real world where you would just use gzip.

    0
  • Jennifer R

    Thursday, September 2nd, 2010 05:44

    7

    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?

    0
  • frio80

    Thursday, September 2nd, 2010 04:02

    8

    Nice article. Lots of good points in here. The last one is up for debate though. The problems with this approach were discussed in the comments here. http://ajaxian.com/archives/want-to-pack-js-and-css-really-well-convert-it-to-a-png-and-unpack-it-via-canvas#comments

    Also, I’ve found that Google Compiler produces smaller file sizes thank YUI Compressor. Give that a shot.

    0
  • Ricky

    Thursday, September 2nd, 2010 05:23

    6

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

    0
  • Richard

    Wednesday, September 1st, 2010 13:56

    5

    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.

    0
  • Julian

    Wednesday, September 1st, 2010 15:14

    2

    Very useful, thanks.

    0
  • Johan de Jong

    Wednesday, September 1st, 2010 16:56

    3

    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!

    0
  • Greg

    Wednesday, September 1st, 2010 19:34

    4

    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!

    0
  • MAtt

    Friday, September 3rd, 2010 03:47

    9

    Nice tips there! There are many others ways of loading JavaScript faster or after page loads.

    0
  • skillguru

    Friday, September 3rd, 2010 17:16

    10

    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.

    0
  • Appu

    Wednesday, September 28th, 2011 19:05

    16

    Nice article. I had such issues with one of my sites.Now It is working properly. Thanks a lot

    0
  • Nick

    Thursday, February 16th, 2012 16:04

    17

    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.

    0
  • Mark

    Wednesday, February 22nd, 2012 20:56

    18

    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!

    0
  • Camry

    Wednesday, July 27th, 2011 08:59

    15

    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.

    0
  • Kami

    Wednesday, May 18th, 2011 19:11

    14

    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?

    0
  • Michael

    Tuesday, September 7th, 2010 09:34

    11

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

    Thanks for the tips.

    0
  • Florian Schommertz

    Friday, September 10th, 2010 13:39

    12

    *Clean* Jscript that uses javascripts own »for loops« instead of jquery for everything.

    0
  • Brett Widmann

    Sunday, January 16th, 2011 02:49

    13

    These are amazing tips! My java should load super fast with no issues now!

    0
  • Mark

    Wednesday, February 22nd, 2012 20:56

    18

    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!

    0
  • Nick

    Thursday, February 16th, 2012 16:04

    17

    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.

    0
  • Appu

    Wednesday, September 28th, 2011 19:05

    16

    Nice article. I had such issues with one of my sites.Now It is working properly. Thanks a lot

    0
  • Camry

    Wednesday, July 27th, 2011 08:59

    15

    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.

    0
  • Kami

    Wednesday, May 18th, 2011 19:11

    14

    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?

    0
  • Brett Widmann

    Sunday, January 16th, 2011 02:49

    13

    These are amazing tips! My java should load super fast with no issues now!

    0
  • Florian Schommertz

    Friday, September 10th, 2010 13:39

    12

    *Clean* Jscript that uses javascripts own »for loops« instead of jquery for everything.

    0
  • Michael

    Tuesday, September 7th, 2010 09:34

    11

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

    Thanks for the tips.

    0
  • skillguru

    Friday, September 3rd, 2010 17:16

    10

    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.

    0
  • MAtt

    Friday, September 3rd, 2010 03:47

    9

    Nice tips there! There are many others ways of loading JavaScript faster or after page loads.

    0
  • frio80

    Thursday, September 2nd, 2010 04:02

    8

    Nice article. Lots of good points in here. The last one is up for debate though. The problems with this approach were discussed in the comments here. http://ajaxian.com/archives/want-to-pack-js-and-css-really-well-convert-it-to-a-png-and-unpack-it-via-canvas#comments

    Also, I’ve found that Google Compiler produces smaller file sizes thank YUI Compressor. Give that a shot.

    0
  • Jennifer R

    Thursday, September 2nd, 2010 05:44

    7

    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?

    0
  • Ricky

    Thursday, September 2nd, 2010 05:23

    6

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

    0
  • Richard

    Wednesday, September 1st, 2010 13:56

    5

    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.

    0
  • Greg

    Wednesday, September 1st, 2010 19:34

    4

    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!

    0
  • Johan de Jong

    Wednesday, September 1st, 2010 16:56

    3

    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!

    0
  • Julian

    Wednesday, September 1st, 2010 15:14

    2

    Very useful, thanks.

    0
  • Jacob Seidelin

    Wednesday, September 1st, 2010 14:23

    1

    Please note that the PNG thing is just a stupid trick and should not be used in any serious project in the real world where you would just use gzip.

    0

Comments are closed.

54.81.177.140 - unknown - unknown - US