Which is faster? - modifying css property or adding class in jquery

前端 未结 4 1810
暗喜
暗喜 2021-01-21 00:17

I have about 100 elements in like and am trying to create an animation with jquery.

I need to a

相关标签:
4条回答
  • 2021-01-21 00:31

    According to jsPerf, addClass is noticeably faster by about 50%.

    Here's the jsPerf data for Chrome but in my tests it was about the same using Firefox:

    $('#a1').css({ 'background-color': '#000' }) 82,043 ±0.21% 48% slower

    $('#a1').addClass("style1") 158,876 ±0.83% fastest

    0 讨论(0)
  • 2021-01-21 00:32

    Adding a class to the parent of all these 100 elements will be faster and defining that class in the css file or page.

    .style1 .box{
       //define style here
    }
    

    This way you just have to manipulate the class of only one element and it is definitely faster than modifying each of the 100 element's style using css method.

    How fast? It all depends on the number of lines of code executed in each of the operations which is again dependent on browser to browser.

    If you go with my approach it will definitely be faster.

    0 讨论(0)
  • 2021-01-21 00:33

    which of them is rendered faster in browser:

    Depends on the browser. you should do some tests if it's interesting you.

    Anyway it's not important and very unlikely to be the bottle-neck of your website.
    Avoid micro-optimization, "premature optimization is the root of all evil", you're wasting your time.

    0 讨论(0)
  • 2021-01-21 00:52

    You can even consider using a style tag.

    It could turn to be very fast. For example if you have a lot of elements to modify, let's say 100 elements, as you write your css only once, the DOM will be changed only once.

    HTML:

    <style type="text/css" id="specialStyle"></style>
    <div class="oneHundredElements" id="box1"/>
    <div class="oneHundredElements" id="box2"/>
    ...
    <div class="oneHundredElements" id="box100"/>
    

    SCRIPT:

    <script>
        var css = '.oneHundredElements {background-color:#000;}';
        $('#specialStyle').html(css);
    </script>
    

    http://jsperf.com/foox/4

    0 讨论(0)
提交回复
热议问题