Performance Optimization: How to Load your javascript faster!

 Posted in Web Design 521 days ago Written by: przemek
  • Buffer
  •  21
  • Buffer

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.

Performance Optimization: How to Load your javascript faster!

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.

 Did you enjoy this article and found it useful?

Article was created by

2

Articles


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
Free Website
 

 21 Brilliant Comments - Join Discussion Now!

  • Appu

    Posted 129 days ago
    21

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

    Reply
  • Authors-Book-Publishers

    Posted 192 days ago
    20

    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.

    Reply
  • gmatprep4mba

    Posted 262 days ago
    19

    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?

    Reply
  • Brett Widmann

    Posted 384 days ago
    18

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

    Reply
  • Sure Media

    Posted 458 days ago
    17

    Will be sure to try that out, thanks!

    Reply
  • Florian Schommertz

    Posted 512 days ago
    16

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

    Reply
  • Michael

    Posted 515 days ago
    15

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

    Thanks for the tips.

    Reply
  • AskApache

    Posted 516 days ago
    14

    Hey I hadn’t heard about that png getImageData trick, that sounds very very cool! Thanks!

    Reply
  • skillguru

    Posted 519 days ago
    13

    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.

    Reply
  • MAtt

    Posted 519 days ago
    12

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

    http://www.tutkiun.com/2010/07/load-javascript-after-pageload.html

    Reply
  • trần công nghiệp

    Posted 520 days ago
    11

    nice post ^^ thanks very much ! i have just begun web develope, i think this article help me very much

    Reply
  • Jennifer R

    Posted 520 days ago
    10

    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?

    Reply
  • Ricky

    Posted 520 days ago
    9

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

    Reply
  • frio80

    Posted 520 days ago
    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.

    Reply
  • Greg

    Posted 521 days ago
    7

    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!

    Reply
  • Eric Hynds

    Posted 521 days ago
    6 Reply
  • Kyle Simpson

    Posted 521 days ago
    5

    A couple of notes: If you use a script loader like LABjs, then you:

    1. don’t have to load your scripts at the end, as they are dynamic and in parallel with the rest of the page. it doesn’t hurt, and I still do it generally, but you can safely use LABjs anywhere in your markup and get pretty good results still.

    2. don’t need to do GA’s ugly async code yourself. You can simply load ga.js with the LABjs loader, and in the .wait() callback that fires when it is loaded, simply run your GA init calls directly. This is what I do on all my sites.

    Reply
  • Johan de Jong

    Posted 521 days ago
    4

    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!

    Reply
  • Julian

    Posted 521 days ago
    3

    Very useful, thanks.

    Reply
  • Jacob Seidelin

    Posted 521 days ago
    2

    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.

    Reply
  • ne web

    Posted 521 days ago
    1

    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.

    Reply

 Add Your Own Brilliant Comment:

Tags allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>