Search code examples
htmlcssbrowserrenderingreflow

Does `window.matchMedia` trigger a reflow?


When building a page, I understand it's good practice to try and minimise "layout thrashing" or "reflow", when the browser recalculates the dimensions and position of all the elements on the page. Paul Irish has produced a handy list of the processes that trigger reflows. He says:

Generally, all APIs that synchronously provide layout metrics will trigger forced reflow / layout.

How come the https://developer.mozilla.org/en/docs/Web/API/Window/matchMedia method isn't on this list? Doesn't that involve measuring the window size? Can we use it without worrying about causing reflows?


Solution

  • I believe that the list is correct and matchMedia does not trigger a reflow. All media queries have been carefully designed to not depend on page content. For example, width has been specced as viewport width including the scrollbar so that the result doesn't change regardless of whether there is a scrollbar or not.