Caching Your jQuery Objects - J Query

Problem
You’re logging the various properties of the event object for a mouse move event, and the code lags behind because it uses $('.class name') selectors to find and update table cells with the event data.
Your page contains this HTML code for the log:

and this JavaScript code:

The page also contains a large number (thousands!) of other DOM elements. In a simpler test page, the code performs fine, but in this complex page it is too slow.Solution Cache the jQuery objects returned by the $(...) calls, so the DOM queries only have to be run once:

You may also be able to speed up those selectors considerably; see the next recipe for ways to do that. But simply calling them once each instead of over and over again may be enough of an improvement right there.

Discussion
One of the classic ways to optimize code is to “hoist” repeated calculations out of a loop so you have to do them only once. Any values that don’t change inside the loop should be calculated one time, before the loop starts. If those are expensive calculations,the loop will then be much faster.This works just as well when the “loop” is a series of frequently fired events such as mouse move and the “calculation” is a jQuery selector. Hoisting the selector out of the event handler makes the event handler respond faster.Of course, if you’re calling multiple selectors inside a loop, that will also benefit from moving them outside the loop in the same manner.


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

J Query Topics