'Do I need to check if a browser supports a certain event before adding the event listener

I was just curious I came across the following package Virtual Scroll. And in it when initializing they check for browser support before adding the event listeners. Like so:

if (support.hasWheelEvent) {
    this.#el.addEventListener(
        'wheel',
        this._onWheel,
        this.listenerOptions
    )
}
...ect for all events

and then the support object looks like:

export function getSupport() {
    return {
        hasWheelEvent: 'onwheel' in document,
        hasMouseWheelEvent: 'onmousewheel' in document,
        hasTouch: 'ontouchstart' in document,
        hasTouchWin: navigator.msMaxTouchPoints && navigator.msMaxTouchPoints > 1,
        hasPointer: !!window.navigator.msPointerEnabled,
        hasKeyDown: 'onkeydown' in document,
        isFirefox: navigator.userAgent.indexOf('Firefox') > -1,
    }
}

I was wondering if this is even necessary. Won't the browser just ignore it if it doesn't support the event specified?

I don't get any errors if I do the following in a non touch browser.

const onTouchStart = () => {}
document.addEventListeners('touchstart', onTouchStart)

Is there some kind of performance benefit for checking first or is there a chance of an error being introduced if you don't check for this?

Anyway let me know. Thanks.



Solution 1:[1]

Won't the browser just ignore it if it doesn't support the event specified?

In this example there is no difference (adding listeners), but sometimes you want to call a function that is not supported and it can lead to errors.

For example using Battery Status API isn't supported by Firefox, IE and Safari. Running this code in these browser will throw an error:

navigator.getBattery()

Checking if the function exists first fixes the problem:

if ('navigator' in window && typeof navigator.getBattery === 'function') {
  navigator.getBattery()
}

Is there some kind of performance benefit for checking first or is there a chance of an error being introduced if you don't check for this?

No, as far as I know.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1