开发者

jQuery's swap method time costly

开发者 https://www.devze.com 2023-01-27 10:25 出处:网络
I ran the profiler in firebug and found that the most time costly function being ran in our UI is jQuery\'s .swap(). I can see that this must be associated with the .css() method.

I ran the profiler in firebug and found that the most time costly function being ran in our UI is jQuery's .swap(). I can see that this must be associated with the .css() method.

Here is an image of my profiler:

jQuery's swap method time costly

Obviously, to improve the speed here I need to cut back on calling .css(), but that is quite the project as I use it to set and correct styling of different elements, which has to be completely dynamic.

Is there a better way to speed this up?

I am using jquery.1.4.2. I haven't been able to move on to 1.4.4 be开发者_高级运维cause it breaks quite a few of my scripts for some reason. Would it be be of benefit to extend the swap method from 1.4.4 to 1.4.2? Or would that present more incompatibilities?

What is the swap method and why is it so time costly?


From what I can see looking at the jQuery UI code, .swap() is not called directly by it, the only place in the jQuery framework itself that uses .swap() directly are the .height() and .width() calls when retrieving the computed height/width of an element.

What it does to calculate the sizes when not available directly from the browser is temporarily swaps the style out for the following:

cssShow = { position: "absolute", visibility: "hidden", display: "block" };

Then performs the usual internal getWH() function whilst in that altered style state, and restores.

The partial code borrowed from jQuery:

jQuery.each(["height", "width"], function( i, name ) {
    jQuery.cssHooks[ name ] = {
        get: function( elem, computed, extra ) {
            var val;

            if ( computed ) {
                if ( elem.offsetWidth !== 0 ) {
                    val = getWH( elem, name, extra );

                } else {
                    jQuery.swap( elem, cssShow, function() {
                        val = getWH( elem, name, extra );
                    });
                }

                   // etc.

jQuery UI uses height() and width() functions everywhere, so it is little wonder that the .swap() function figures highly in the profile.

0

精彩评论

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