It can be quite common when working with web apps to need to use Javascript to check for window resizes.

The typical way is to use an event listener on window’s resize event, such as:

function checkForWindowResize() {
    console.log(`Screen width: ${window.innerWidth}`);

    if (window.innerWidth < 600) {
       doSomethingForSmallScreens();
    }
    else {
       doSomethingForLargeScreens();
    }
}

window.addEventListener('resize', checkForWindowResize);

However, this will mean that the checkForWindowResize function will fire every time the window is resized, at every pixel increment/decrement.

This can have huge performance issues if the event listener function is slow to run.

It is quite common that you don’t need all of those events - you only care if it was resized smaller or larger than a certain size.

In those cases there is a nicer alternative where you can use css media query breakpoints. This won’t be suitable for all uses of adding an event listener to the resize event, but it is very useful in many situations.

#javascript #programming #developer

JavaScript’s window.matchMedia (vs resize event listeners)
18.75 GEEK