0

According to Event Loop basics and the video, re-render task is executing after all JS scripts have been completed. The pixel pipeline

But if synchronously add an element to the DOM and measure width or height, without waiting for a re-render - it works! It's even possible to change element's content and measure again - still working.

So, why does this works?

let element = document.createElement('div');
Object.assign(element.style, {
  'position': 'absolute',
  'float': 'left',
  'whiteSpace': 'nowrap',
  'visibility': 'hidden',
  'font': '12px arial',
  'display': 'inline-block'
});

element.innerText = 'some text';
document.querySelector('body').appendChild(element);

// Why does it work? According to the video, 
// I need to wait when async render task be completed, isn't it?
console.log(element.offsetWidth);

1 Answers1

1

It's true that the browser ordinarily batches changes to the dom and applies them all at once when the animation frame comes around. But if you ask for a value which depends on that rendering being complete (such as getting the width), the browser may be forced to immediately do a reflow in order to provide an answer to you. This should usually be avoided, since it can be a performance problem.

Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98