Coder Social home page Coder Social logo

addityasingh / add-eventlistener-with-options Goto Github PK

View Code? Open in Web Editor NEW
9.0 2.0 1.0 1.32 MB

A utility function to check if EventTarget.addEventListener supports adding passive events

License: MIT License

JavaScript 82.98% HCL 17.02%
event-listener passive touch npm nodejs addeventlistener

add-eventlistener-with-options's Introduction

add-eventlistener-with-options

A utility function to check if EventTarget.addEventListener supports adding passive (or capture, once) event options.

NPM

Build status

Build Status coverage

npm status

downloads version

Story behind Passive event listeners

Passive event listeners are a new feature in the DOM spec that enable developers to opt-in to better scroll performance by eliminating the need for scrolling to block on touch and wheel event listeners. Developers can annotate touch and wheel listeners with {passive: true} to indicate that they will never invoke preventDefault. This feature shipped in Chrome 51, Firefox 49 and landed in WebKit.

The problem

Smooth scrolling performance is essential to a good experience on the web, especially on touch-based devices. All modern browsers have a threaded scrolling feature to permit scrolling to run smoothly even when expensive JavaScript is running, but this optimization is partially defeated by the need to wait for the results of any touchstart and touchmove handlers, which may prevent the scroll entirely by calling preventDefault() on the event. While there are particular scenarios where an author may indeed want to prevent scrolling, analysis indicates that the majority of touch event handlers on the web never actually call preventDefault(), so browsers often block scrolling unneccesarily. For instance, in Chrome for Android 80% of the touch events that block scrolling never actually prevent it. 10% of these events add more than 100ms of delay to the start of scrolling, and a catastrophic delay of at least 500ms occurs in 1% of scrolls.

Solution: the 'passive' option

Now that we have an extensible syntax for specifying options at event handler registration time, we can add a new passive option which declares up-front that the listener will never call preventDefault() on the event. If it does, the user agent will just ignore the request (ideally generating at least a console warning).

Now rather than having to block scrolling whenever there are any touch or wheel listener, the browser only needs to do this when there are non-passive listeners (see TouchEvents spec). passive listeners are free of performance side-effects.

This package provides a smooth fallback implementation to use the { passive: true } option in newer browsers, while falling back to false value in older ones. Additionally, you could also use the method to use the capture and once options.

Syntax

addEventListenerWithOptions(target, 
  eventName, 
  listener, 
  options, 
  optionName);
  • target: The EventTarget element to use as the target of the event
  • eventName: Name of the event to be handled using the event listener. E.g. touchstart, touchend
  • listener: The event listener callback to be called on the event
  • options: Additional options
  • optionName: Defaults to passive. Use [once, capture] to override.

Installation

Use it with npm as

npm install add-event-listener-with-options

Example

  • To add the passive event listeners as default

ES6 syntax

import addEventListenerWithOptions from 'add-eventlistener-with-options';

addEventListenerWithOptions(window, 'touchstart', () => {
    // Execute callback code
});
  • The default option is passive, but you can even add capture or once options by passing them as the last parameter
addEventListenerWithOptions(window, 'touchstart', () => {
    // Execute callback code
}, {}, 'capture');

Performance test

There is a video showing the comparison of performance on CNN website here

![demo video](https://cloud.githubusercontent.com/assets/39191/16223871/cab9f508-379f-11e6-8154-1d0a005ad071.png)

Additionally, I tested the change with below code and the Devtools Timline data before and after the change are shown below for a sample Redux application. The number of frames in green (< 16ms) is increased after adding the passive option as compared below:

Before

window.addEventListener('touchstart', (e) => {
  console.log('e.defaultPrevented', e.defaultPrevented);  // will be false 
  for (let i =0; i< 100; i++) {
    console.log(`i ${i}`);
    e.preventDefault(); // prevents the scroll because the event handler is not passive 
  }

  console.log('e.defaultPrevented', e.defaultPrevented);  // true 
});

Before Passive

After

addEventListenerWithOptions(window, 'touchstart', (e) => {
  console.log('e.defaultPrevented', e.defaultPrevented);  // will be false 
  for (let i =0; i< 100; i++) {
    console.log(`i ${i}`);
    e.preventDefault(); // does nothing since the listener is passive 
  }

  console.log('e.defaultPrevented', e.defaultPrevented);  // still false 
});

After Passive

Reference and Credits

Most of the sources for implementing this comes from the Web Platform Incubator Community Group suggestion on EventListenerOptions

add-eventlistener-with-options's People

Contributors

addi90 avatar addityasingh avatar dependabot[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

Forkers

vishal11

add-eventlistener-with-options's Issues

Cannot npm install "No valid versions available for add-event-listener-with-options"

└─( 2 ) ❱❱❱ npm install add-event-listener-with-options --verbose                                                                                                                                               1 ⏎  +2860 16:30 ❰─┘
npm info it worked if it ends with ok
npm verb cli [ '/home/michael-heuberger/.nvm/versions/node/v8.1.0/bin/node',
npm verb cli   '/home/michael-heuberger/.nvm/versions/node/v8.1.0/bin/npm',
npm verb cli   'install',
npm verb cli   'add-event-listener-with-options',
npm verb cli   '--verbose' ]
npm info using [email protected]
npm info using [email protected]
npm verb npm-session 619a6de5c451cce6
npm http fetch GET 200 https://registry.npmjs.org/add-event-listener-with-options 21ms (from cache)
npm verb type tag
npm verb stack add-event-listener-with-options: No valid versions available for add-event-listener-with-options
npm verb stack     at pickManifest (/home/michael-heuberger/.nvm/versions/node/v8.1.0/lib/node_modules/npm/node_modules/pacote/node_modules/npm-pick-manifest/index.js:19:11)
npm verb stack     at fetchPackument.then.packument (/home/michael-heuberger/.nvm/versions/node/v8.1.0/lib/node_modules/npm/node_modules/pacote/lib/fetchers/registry/manifest.js:39:14)
npm verb stack     at tryCatcher (/home/michael-heuberger/.nvm/versions/node/v8.1.0/lib/node_modules/npm/node_modules/bluebird/js/release/util.js:16:23)
npm verb stack     at Promise._settlePromiseFromHandler (/home/michael-heuberger/.nvm/versions/node/v8.1.0/lib/node_modules/npm/node_modules/bluebird/js/release/promise.js:512:31)
npm verb stack     at Promise._settlePromise (/home/michael-heuberger/.nvm/versions/node/v8.1.0/lib/node_modules/npm/node_modules/bluebird/js/release/promise.js:569:18)
npm verb stack     at Promise._settlePromise0 (/home/michael-heuberger/.nvm/versions/node/v8.1.0/lib/node_modules/npm/node_modules/bluebird/js/release/promise.js:614:10)
npm verb stack     at Promise._settlePromises (/home/michael-heuberger/.nvm/versions/node/v8.1.0/lib/node_modules/npm/node_modules/bluebird/js/release/promise.js:693:18)
npm verb stack     at Async._drainQueue (/home/michael-heuberger/.nvm/versions/node/v8.1.0/lib/node_modules/npm/node_modules/bluebird/js/release/async.js:133:16)
npm verb stack     at Async._drainQueues (/home/michael-heuberger/.nvm/versions/node/v8.1.0/lib/node_modules/npm/node_modules/bluebird/js/release/async.js:143:10)
npm verb stack     at Immediate.Async.drainQueues (/home/michael-heuberger/.nvm/versions/node/v8.1.0/lib/node_modules/npm/node_modules/bluebird/js/release/async.js:17:14)
npm verb stack     at runCallback (timers.js:800:20)
npm verb stack     at tryOnImmediate (timers.js:762:5)
npm verb stack     at processImmediate [as _immediateCallback] (timers.js:733:5)
npm verb cwd /home/michael-heuberger/code/videomail-client
npm verb Linux 4.10.0-26-generic
npm verb argv "/home/michael-heuberger/.nvm/versions/node/v8.1.0/bin/node" "/home/michael-heuberger/.nvm/versions/node/v8.1.0/bin/npm" "install" "add-event-listener-with-options" "--verbose"
npm verb node v8.1.0
npm verb npm  v5.3.0
npm ERR! code ENOVERSIONS
npm ERR! No valid versions available for add-event-listener-with-options
npm verb exit [ 1, true ]

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/michael-heuberger/.npm/_logs/2017-07-15T04_30_39_627Z-debug.log

Implement and publish the package

  • Publish to npm
  • Do npm install in another project to make sure its working
  • Integrate webpack to generate UMD build
  • Add documentation for the package

Documentation

  • Add default option as { passive: true } and allow others to be passed
  • Remove the sanitizeOptions function
  • Don't call isPassiveSupported() as default in addEventListenerWithOptions. Accept it as a parameter whose default value is isPassiveSupported
  • Add small site to show performance with/ without
  • Add Devtool timeline for above

Error: Cannot find module 'add-eventlistener-with-options' from ...

Bumped from v1.25.0 to 1.25.3 in my https://github.com/binarykitchen/videomail-client package and now unit tests fail.

Here a stack trace, not very helpful I am afraid:

[17:02:44] Starting 'test'...
Error: Cannot find module 'add-eventlistener-with-options' from '/Users/michael-heuberger/code/videomail-client/src/wrappers/visuals'
internal/streams/legacy.js:59
      throw er; // Unhandled stream error in pipe.
      ^

Error: javascript required
    at Stream.<anonymous> (/Users/michael-heuberger/code/videomail-client/node_modules/browser-run/index.js:35:34)
    at _end (/Users/michael-heuberger/code/videomail-client/node_modules/through/index.js:65:9)
    at Stream.stream.end (/Users/michael-heuberger/code/videomail-client/node_modules/through/index.js:74:5)
    at Stream.method [as end] (/Users/michael-heuberger/code/videomail-client/node_modules/duplexer/index.js:47:39)
    at Stream.<anonymous> (/Users/michael-heuberger/code/videomail-client/node_modules/throughout/index.js:7:25)
    at _end (/Users/michael-heuberger/code/videomail-client/node_modules/through/index.js:65:9)
    at Stream.stream.end (/Users/michael-heuberger/code/videomail-client/node_modules/through/index.js:74:5)
    at Stream.onend (internal/streams/legacy.js:44:10)
    at emitNone (events.js:111:20)
    at Stream.emit (events.js:208:7)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

The interesting part is probably

internal/streams/legacy.js:59
      throw er; // Unhandled stream error in pipe.

and

Error: javascript required

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.