开发者

how to determine how many jQuery objects are on a page?

开发者 https://www.devze.com 2023-01-01 04:27 出处:网络
C开发者_StackOverflow社区an I determine the number of jQuery objects on a page? I want to use the number of elements as a sort of weak benchmark for page complexity.I\'m thinking that if I can reduc

C开发者_StackOverflow社区an I determine the number of jQuery objects on a page?

I want to use the number of elements as a sort of weak benchmark for page complexity. I'm thinking that if I can reduce the number of elements that jQuery knows about , the page might run more efficiently.

Does this make sense?

Is it as simple as doing a * select and counting the results?


related:

How can I clear content without getting the dreaded “stop running this script?” dialog?


http://api.jquery.com/size/

var elementCount = $('*').size();

Although this might be more what you want:

var elementCount = $('body').find('*').size()


var n= 0;
for (var i in jQuery.cache)
    n++;

Now n holds the number of elements jQuery has ‘touched’ (added data to, such as event handlers).

Previously this used to be a whole lot, as it would ‘touch’ every element it was even checking for data. This unpleasantness is fixed in jQuery 1.4.

As for clearing content, yes, you can use innerHTML= '' to remove all the content without giving jQuery the chance to detach its data so very slowly. If you know there are no ‘touched’ elements inside the element that's a win, but otherwise it's a potential memory leak until the page is reloaded, as unused jQuery.cache data stays around.

Using live()/delegate() event binding avoids adding data to its target elements, which can allow you to use this short-cut more freely. However if you have a lot of events to bind and they're not selectors that are very easy to match quickly, this can make event handling slow.

(Because there is no browser-native speedup like querySelectorAll for matching elements against a particular selector as delegation needs to do; this is proposed for Selectors-API level 2.)


var elementCount = $('*').length;

This doesn't really have much to do with jQuery except insofar as it's a handy way to get the answer.

0

精彩评论

暂无评论...
验证码 换一张
取 消