Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

136
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda