02.06.2013 Views

jQuery Cookbook - Cdn.oreilly.com - O'Reilly

jQuery Cookbook - Cdn.oreilly.com - O'Reilly

jQuery Cookbook - Cdn.oreilly.com - O'Reilly

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

}<br />

html[++h] = ' ';<br />

html[++h] = e(name.last);<br />

html[++h] = '';<br />

html[++h] = e(name.street);<br />

html[++h] = '';<br />

html[++h] = e(name.city);<br />

html[++h] = ', ';<br />

html[++h] = e(name.state);<br />

html[++h] = ' ';<br />

html[++h] = e(name.zip);<br />

html[++h] = '';<br />

}<br />

html[++h] = '';<br />

html[++h] = '';<br />

$('#container')[0].innerHTML = html.join('');<br />

$.getJSON( 'names/names-1000.json', function( json ) {<br />

fillTable( json.names );<br />

});<br />

});<br />

The new code requires the HTML code in your document to be changed to the<br />

following:<br />

<br />

<br />

On one test system in IE 7, the new code runs in 0.2 seconds <strong>com</strong>pared with 7 seconds<br />

for the original code. That’s 35 times faster!<br />

Granted, the code is not as clean and elegant as the original, but your site’s visitors will<br />

never know or care about that. What they will notice is how much faster your page<br />

loads.<br />

Discussion<br />

Sometimes you’ll get lucky and find that one specific optimization is all it takes to fix<br />

a performance problem. Sometimes, as in this recipe, you’ll need several tricks to get<br />

the speed you want.<br />

The biggest speed boost in this code <strong>com</strong>es from inserting a single element with<br />

all its children in a single DOM operation, instead of inserting a lengthy series of<br />

elements one by one. In order to do this, you need to generate the entire table as<br />

HTML. That means you need to paste together a large number of strings to build the<br />

HTML, which can be very fast or very slow depending on how you do it. And with<br />

1,000 items to loop though, it’s worth finding the fastest way to write the loop itself.<br />

You may wonder, “Is this still <strong>jQuery</strong> code? It looks like plain old JavaScript!” The<br />

answer is yes, and yes. It’s quite all right to mix and match <strong>jQuery</strong> code with other<br />

JavaScript code. You can use simpler <strong>jQuery</strong> ways of coding in most of your site, and<br />

5.11 Loading Tables Faster | 111

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!