Luke Murray

Javascript functions can cause layout thrashing

March 25, 2021

Today I was profiling an application which uses autocomplete and I noticed that in the chrome dev tools it said ther ewas a forced layout occuring.

Turns out many of the javascript APIs which ask for the size or location of a DOM element will cause the browser to synchronously calculate the style and layout. Paul Irish has an excellent list of most of these methods

In my case I am positioning a dropdown based on the current window selection's range. Whenever the user types a character I call range.getBoundingClientRect() which is triggering a layout reflow in the browser.

I don't have a great solution for this yet but I did find one other place in my application that was triggering forced layouts.

If you use tippyjs or popperjs then you may ant to set your boundary to "viewport". The default is to use "clippingParents" which will cause a layout to occur.