Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

144
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!