📜 ⬆️ ⬇️

Optimization with closures

It is given - once a second the AJAX script is twitching, there are several calls to the same function (let's call it updater) with different arguments. The function, in accordance with the arguments, updates a certain set of DOM elements (changes content, hides, shows) on the current page. Used jQuery, effects, etc. Those. About such code comes to the client ...
updater( 'id1' , 10, 20);
updater( 'id33' , 11, 22);
updater( 'id181' , 102, 27);


* This source code was highlighted with Source Code Highlighter .

The problem is that after an increase in the number of called functions (an increase in the number of typical blocks) everything is terribly slow, a lot of time is spent on jQuery, the choice of DOM elements by selectors.

It is required whenever possible quickly and without serious consequences, without changing a layout and without refusing jQuery to optimize the process.

Solution - we make a function that generates for each type block a new update function using closures. At the same time, all "long" operations ($ ('. Class .class'). Parent ('div'), etc., should be cached.

Let it be earlier
function updater(rootId, arg2, arg3)
{
$( '#' +rootId+ ' .some .selector' ).some().action();
$( '#' +rootId+ ' .some2 .selector3' ).some().action();
}


* This source code was highlighted with Source Code Highlighter .

We pregenerate all the "updates" and call the right one - all the results of the "long" operations are cached, leaving only the updates of the elements and manipulations with them, depending on the remaining arguments.
function makeUpdater(rootId) {
if ($( '#' +rootId).length>0)
{
var someVar = $( '#' +rootId+ ' .some .selector' );
var someVar2 = $( '#' +rootId+ ' .some2 .selector3' );
return function (arg2, arg3) {
someVar.some().action();
someVar2.some().action();
// do smth else...
}
}
else
return function (arg2, arg3) {}
}

var updaters = new Array();
var idx = 0;
$( 'div.rootElement' ).each( function () {
updaters[idx++] = makeUpdater($( this ).attr( 'id' ));
});

function updater(rootId, arg2, arg3) {
updaterFnc = // rootId updaters
updaterFnc(arg2, arg3);
}


* This source code was highlighted with Source Code Highlighter .

')
UPD: An alternative solution is selector caching: habrahabr.ru/blogs/jquery/63145

Source: https://habr.com/ru/post/63119/


All Articles