30 December 2011

Load content asynchonrously: a simple speedup

Here’s a common tactic for speeding up the perceived page load time on your site:

Only render important and quick-to-compute stuff in the initial page load and load everything else via AJAX.

To show just how easy it is to do this, I have coded up a very short script (195 characters when minified)—called async-include—which you can use as so:

1. Include the aysnc-include.js script on your page

2. Add an HTML snippet on your page like this:

<div data-async-url="/some-url/"></div>

And when the page loads, it will make an AJAX request to the url specified in the data-async-url attribute and replace the HTML element with the returned content.

This is really useful for widgets on a page that are slow to compute and not the primary focus, and it’s so simple that it shouldn’t hurt development time. We used something like this on hunch for a variety of things, including a widget on the side of the page of “people to follow”. eBay and many other companies use a similar asynchronous loading technique to provide a snappier user experience.

This asynchronous loading approach can be made increasingly complex, depending on what you need from it, e.g., it could load after different events or delays, or it could load things non-asynchronously for googlebot. Check out the code on my github page.

Update: I was curious about the performance of class selection vs attribute selection in JavaScript—this jsPerf test suggests that they’re reasonably equivalent operations for a browser and maybe the main time difference is jQuery having to do more complex parsing with the attribute selector.

comments powered by Disqus

Peter Coles

Peter Coles

is a software engineer who lives in NYC, works at Ringly, and blogs here.
More about Peter »

github · soundcloud · @lethys · rss

It’s time to get big money out of politics. Join the kick-started campaign to put government back in the hands of the people. Pledge mayday.us now