Using $ .css () without a selector increases performance?

JQuery allows us to directly use the $ .css () method and pass the original DOM element as the first parameter. For example, if I want to set 'a' to the width of myDiv, jQuery allows this syntax:

(OPTION 1):

var elem = document.getElementById('myDiv'); var a = $.css(elem, 'width'); 

instead (OPTION 2):

 var a = $('#myDiv').css('width'); 

Option 1 does not require a selector, and it seems to rely on a global jQuery object, rather than creating a new one. I can not find documentation in jQuery API or online about this method. I suppose this will be an increase in performance, especially when jQuery objects are required in the animation. Any reason I should not use this method?

Thanks!

EDIT: Perf tests show that option 1 is a bit faster. It doesn't seem like there is any reason not to use $ .css () directly. Thanks everyone for the answers!

+4
source share
3 answers

Yes, the first is a little faster. But it can only get the css value.

I did a perfection test here: http://jsperf.com/jquery-css-signature You can review it and check other parameters.

Now that the facts are established, at this level of performance optimization, I don’t think it is worth the overhead. Go with a more understandable / supported way to get the same result. The performance advantage is not large enough to really deal in most cases.

+1
source

Everything that accepts jQuery from an equation makes it faster. Using your own getElementById instead of passing the string you want to process, you increase the speed.

Even faster would be to use native getComputedStyle :

 var elem = document.getElementById('myDiv'); var a = window.getComputedStyle(elem).width; 

Note that older versions of IE use currentStyle instead, so you can normalize it like this:

 window.getComputedStyle = window.getComputedStyle || function(e) {return e.currentStyle;}; 

For more information on using plain JavaScript, see Vanilla JS

+1
source

Option 2 after some type checking and analysis will be about the same as option 1. I cannot imagine that the difference in performance (if any) is significant.

If you are worried about performance when accessing an element again, it is best to do all the searches once and reuse this:

 var elem = $('#myDiv'); var a = elem.css('width'); elem.css('height', '100px'); // etc. 
0
source

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


All Articles