4

I've got the following code I need to make sure is performance sensitive:

var $content = $(htmlString);

//Stop new element from triggering reflow? 
$content.css('display', 'none');

//add slide to DOM
$content.appendTo(options.els.$slider);

I can't remember if a reflow is triggered on any DOM manipulation or if there are exceptions like adding an out of the flow element to the DOM. Will the above code cause a reflow if options.els.$slider is in the flow?

styke
  • 2,116
  • 2
  • 23
  • 51

2 Answers2

2

The hide method (or the css method as the updated question shows) sets the display property to none:

display: none;

Which will cause the element to be removed from the normal document flow. If the requirement is to not remove the element from the normal document flow, change the visibility CSS property instead:

$content.css('visibility', 'hidden');

Setting the display property before adding it to the DOM, however, should not cause a reflow.

Note that changing the visibility once the element is added to the DOM will cause a repaint, however. Paint events can be profiled using a number of different tools, including Chrome Developer Tools on the timeline tab.

Community
  • 1
  • 1
Drew Gaynor
  • 8,292
  • 5
  • 40
  • 53
  • Considering I am setting the elements display property to none before I insert into the DOM (am I correct in assuming that's what's happening?) will it trigger a reflow? This is what I am interested in. – styke Oct 01 '15 at 17:34
  • @styke See my updated answer. The document flow shouldn't change as it's the element was out of the flow before it was inserted into the DOM. A repaint might be a different story though- I recommend using a tool as I mentioned in the answer to check for sure and do any profiling you may need. – Drew Gaynor Oct 01 '15 at 17:55
1

Each browser has it's own method of determining that, but typically, if your code is not causing any other elements to change, reflow won't happen. Just because you're appending to the DOM, doesn't mean the browser should repaint the page. You should be good.

Mike S.
  • 969
  • 5
  • 13