jQuery Cookbook - Cdn.oreilly.com - O'Reilly
jQuery Cookbook - Cdn.oreilly.com - O'Reilly
jQuery Cookbook - Cdn.oreilly.com - O'Reilly
You also want an ePaper? Increase the reach of your titles
YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.
};<br />
});<br />
That is a bit simpler than our .toggleAttr() method, but it’s only useful for the<br />
checked attribute and nothing else. What would we do if we later needed<br />
that .toggleEnable() method? Duplicate the whole thing and change a few names?<br />
The extra work in .toggleAttr() buys us a lot of flexibility: we now can write a whole<br />
family of attribute togglers as straightforward one-liners.<br />
Check the documentation for the version of <strong>jQuery</strong> you’re using before<br />
writing new utility methods like this. It’s always possible that similar<br />
methods could be added to future versions of <strong>jQuery</strong>, saving you the<br />
trouble of writing your own.<br />
5.8 Finding the Bottlenecks<br />
Problem<br />
Your site is too slow to load or too slow to respond to clicks and other user interaction,<br />
and you don’t know why. What part of the code is taking so much time?<br />
Solution<br />
Use a profiler, either one of the many available ones or a simple one you can code<br />
yourself.<br />
Discussion<br />
A profiler is a way to find the parts of your code that take the most time. You probably<br />
already have at least one good JavaScript profiler at your fingertips. Firebug has one,<br />
and others are built into IE 8 and Safari 4. These are all function profilers: you start<br />
profiling, interact with your page, and stop profiling, and then you get a report showing<br />
how much time was spent in each function. That may be enough right there to tell you<br />
which code you need to speed up.<br />
There are also some profilers specific to <strong>jQuery</strong> that you can find with a web search for<br />
jquery profiler. These let you profile selector performance and look more deeply at<br />
<strong>jQuery</strong> function performance.<br />
For really detailed profiling, where you need to analyze individual sections of code<br />
smaller than the function level, you can write a simple profiler in just a few lines of<br />
code. You may have coded this ad hoc classic:<br />
var t1 = +new Date;<br />
// ... do stuff ...<br />
var t2 = +new Date;<br />
alert( ( t2 - t1 ) + ' milliseconds' );<br />
5.8 Finding the Bottlenecks | 101