JavaScript window resize event

前端 未结 13 776
余生分开走
余生分开走 2020-11-22 00:58

How can I hook into a browser window resize event?

There\'s a jQuery way of listening for resize events but I would prefer not to bring it into my project for just t

13条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 01:26

    The resize event should never be used directly as it is fired continuously as we resize.

    Use a debounce function to mitigate the excess calls.

    window.addEventListener('resize',debounce(handler, delay, immediate),false);

    Here's a common debounce floating around the net, though do look for more advanced ones as featuerd in lodash.

    const debounce = (func, wait, immediate) => {
        var timeout;
        return () => {
            const context = this, args = arguments;
            const later = function() {
                timeout = null;
                if (!immediate) func.apply(context, args);
            };
            const callNow = immediate && !timeout;
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
            if (callNow) func.apply(context, args);
        };
    };
    

    This can be used like so...

    window.addEventListener('resize', debounce(() => console.log('hello'),
    200, false), false);
    

    It will never fire more than once every 200ms.

    For mobile orientation changes use:

    window.addEventListener('orientationchange', () => console.log('hello'), false);
    

    Here's a small library I put together to take care of this neatly.

提交回复
热议问题