Velocity 08: High Performance AJAX Applications


Julien Lecomte from Yahoo! is speaking about creating performant AJAX applications. The most important point: plan for performance from day 1. Interestingly many of his initial points are about telling the developer to work with the product manager and not just say "no."

Julien references an Web Site Optimization: 13 Simple Steps by Stoyan Stefanov. Here's some tips:

Less is more. Don't do unnecessary things.

Break rules. Make compromises and break best practices when needed. For example, you might decide to forgo CSS. Especially CSS expressions.

Work on improving perceived performance. Cheat by making users think things are done before they are.

Measure performance. Test using a setup similar to the user's configuration. Profile your code during development. Automate profiling and performance testing. Keep historical records of how feature perform.

Minify CSS and Javascript files. Use something like the YUI Compressor. Stay away from compression schemes that require run time compression. You can also combine the CSS and JAvascript files. Optimize images.

Loading and parsing HTML, CSS, and JavaScript code is costly. Be concise and write less code. Make good use of libraries. Splitting JS libraries into bundles for specific uses might save time.

Close HTML tags. Unclosed tags take longer to parse. Load assets (even images) on demands.

Most DOM events can be accomplished before the onload even has fired. You can also load the scripts after the page has fully loaded.

In JavaScript a lookup is done each time a variable is accessed. Declaring variables with the var keyword and making them local helps. Avoid global variables at all costs. Avoid with. You can use a local variable to "cache" the value of a variable outside the current scope when it's going to be accessed repeatedly.

Limit the number of event handlers. Attaching a even handler to hundreds of elements is very costly and can be the source memory leaks.

Reflows happen when the DOM tree is manipulated. You can minimize reflows by taking advantage of browser built-in optimizations. For example, modifying an invisible element doesn't trigger reflow.

Use onmousedown instead of onclick to take advantage of the time between the start of the button press and the release.

Avoid using JavaScript for layout. Use CSS where possible.

Never resort to a synchronous XHR. Asynchronous programming is more complicated but it's worth it. Deal with network timeouts programmatically.

If you validate user data on the browser, 99.9% of the time, the request will succeed, so lock the affected elements, let the user know something's happening, and process the request while the user continues to use the application.

Use JSON rather than XML. Consider local storage and just process diffs. Multiplex AJAX requests where you can.