").css({ "background-color" : "red", ...">

JQuery - readability and performance (?)

Given the jQuery code snippets that does the same thing:

$("<div />").css({ "background-color" : "red", "color" : "white", "border" : "solid 1px black" }) .appendTo( someElement ); 

and

 $("<div style='background-color:red;color:white;border:solid 1px black' />") .appendTo( someElement ); 

The first, in my opinion, is more readable, but is there a difference in performance between the two? Or is the performance difference so small that readability should go before declaring an explicit ad?

[Edit: clarification]

Using CSS and style is an example. This may be the addition of many other attributes / values.

+4
source share
2 answers

Well ... it depends. If you insert a lot of it, the second one is faster because less repetition occurs (but the parsing starts first ... and this part depends on the browser, whether it is parsing or explicit CSS definition faster).

The html line you use is cached as a document fragment, reused for future insertions, so the second one will have all the whole line styles and everything is ready for cloning immediately, and not set styles every time, so it’s much faster to loop.

Unfortunately, because of this caching, it’s hard to check, because the best way to check ... is the repeating loop for which it is optimized. Here is a demo test demo that works in Chrome or Firefox / Firebug, just open the console to see the results (the page will lag while it opens ... running tests):

http://jsfiddle.net/XAece/

In this test on my machine for 100,000 iterations in Chrome:

  • .css() method: 4654ms
  • inline style method: 4056 ms
  • $(html, props) method: 5816 ms

For Firefox:

  • .css() method: 8648ms
  • inline style method: 3371ms
  • $(html, props) method: 10250 ms

As a side note, there is another method (the third in the test above), $(html, props) , where you can attach event handlers, use text to get the encoded inner text, etc:

 $("<div />", { css: { "background-color" : "red", "color" : "white", "border" : "solid 1px black" }, click: function() { alert('You clicked me!'); } }).appendTo( someElement ); 
+6
source

using:

 $('<div class="someClass" />').appendTo(someElement); 

and you save both

or

 $('<div style="\ border:1px solid #888;\ padding:2px;\ " />').appendTo(someElement); 
+4
source

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


All Articles