Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

143
Vistas
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.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda