javascript - How to create jQuery plugin to cache jQuery object as shown below -
problem is, in case of e
of type htmlelement
this causes performance issue $(e) !== $(e)
instead of reusing jquery object, jquery creates new object each time when call $(e)
$(e).attr(.... $(e).css(... $(e).find(....
for each statement, new jquery object created , performance increases when do
var $e = $(e); $e.attr(.... $e.css(... $e.find(....
so decided cache rewriting $ below. instead of changing huge code.
var $old = window.$; var $ = function(o){ if(typeof htmlelement === "object" ? o instanceof htmlelement : o && typeof o === "object" && o !== null && o.nodetype === 1 && typeof o.nodename==="string"){ o.__$ = o.__$ || $old(o); return o.__$; } return $old(o); }; $.prototype = $old.prototype;
after $(e) === $(e)
returns true, , in context of page, if called multiple times, runs pretty fast.
however, $.trim, $.isarray
function gone, have large code base depends upon jquery, want improve speed of jquery caching.
while see trying achieve, don't think modifying jquery here solution.
in example code
$(e).attr(...); $(e).css(...); $(e).find(...);
this cause jquery re-evaluate selector 3 times, , yes, going slower if cached. i'd argue modifying jquery caching wrong solution.
normally in programming "cache" result of fetch variable make our modification on (rather re-fetch)
var e = $(e); e.attr(...); e.css(...); e.find(...);
or jquery's chaining, can in 1 line
$(e).attr(...).css(...).find(...); //(wrap if desired)
i think changing behavior of jquery auto-cache promotes bad practice of not thinking/caring performance of code written.
e.g. if there "cool js library" did sql...
$sql("select * table foo name='blah'").updatetimestamp(); $sql("select * table foo name='blah'").set('type','raincoat'); $sql("select * table foo name='blah'").set('price',57.50);
it obvious performance of suck due re-selecting results. think jquery developers need remember selector running query (sometimes fast!) still query shouldn't abused calling multiple times if not needed.
(ps i'm joking suggesting client side sql query library thing, ditto select *... example)
Comments
Post a Comment