jQuery Cookbook - Cdn.oreilly.com - O'Reilly
jQuery Cookbook - Cdn.oreilly.com - O'Reilly
jQuery Cookbook - Cdn.oreilly.com - O'Reilly
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
The page also contains a large number (thousands!) of other DOM elements. In a simpler<br />
test page, the code performs fine, but in this <strong>com</strong>plex page it is too slow.<br />
Solution<br />
Cache the <strong>jQuery</strong> objects returned by the $(...) calls, so the DOM queries only have<br />
to be run once:<br />
var<br />
$clientX = $('.clientX'),<br />
$clientY = $('.clientY'),<br />
$pageX = $('.pageX'),<br />
$pageY = $('.pageY'),<br />
$screenX = $('.screenX'),<br />
$screenY = $('.screenY');<br />
$('html').mousemove( function( event ) {<br />
$clientX.html( event.clientX );<br />
$clientY.html( event.clientY );<br />
$pageX.html( event.pageX );<br />
$pageY.html( event.pageY );<br />
$screenX.html( event.screenX );<br />
$screenY.html( event.screenY );<br />
});<br />
You may also be able to speed up those selectors considerably; see the next recipe for<br />
ways to do that. But simply calling them once each instead of over and over again may<br />
be enough of an improvement right there.<br />
Discussion<br />
One of the classic ways to optimize code is to “hoist” repeated calculations out of a<br />
loop so you have to do them only once. Any values that don’t change inside the loop<br />
should be calculated one time, before the loop starts. If those are expensive calculations,<br />
the loop will then be much faster.<br />
This works just as well when the “loop” is a series of frequently fired events such as<br />
mousemove and the “calculation” is a <strong>jQuery</strong> selector. Hoisting the selector out of the<br />
event handler makes the event handler respond faster.<br />
Of course, if you’re calling multiple selectors inside a loop, that will also benefit from<br />
moving them outside the loop in the same manner.<br />
106 | Chapter 5: Faster, Simpler, More Fun