https://github.com/wessberg/connection-observer
An API that provides a way to asynchronously observe the connectedness of a target Node inside a document
https://github.com/wessberg/connection-observer
asynchronous connectedcallback connectedness connection disconnected disconnectedcallback dom mutationobserver observer
Last synced: 7 months ago
JSON representation
An API that provides a way to asynchronously observe the connectedness of a target Node inside a document
- Host: GitHub
- URL: https://github.com/wessberg/connection-observer
- Owner: wessberg
- License: mit
- Created: 2019-02-12T23:56:39.000Z (over 6 years ago)
- Default Branch: master
- Last Pushed: 2024-03-28T15:00:35.000Z (over 1 year ago)
- Last Synced: 2025-03-11T07:46:19.489Z (7 months ago)
- Topics: asynchronous, connectedcallback, connectedness, connection, disconnected, disconnectedcallback, dom, mutationobserver, observer
- Language: TypeScript
- Size: 605 KB
- Stars: 14
- Watchers: 2
- Forks: 2
- Open Issues: 8
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- Contributing: CONTRIBUTING.md
- Funding: .github/FUNDING.yml
- License: LICENSE.md
- Code of conduct: CODE_OF_CONDUCT.md
Awesome Lists containing this project
README
> An API that provides a way to asynchronously observe the connectedness of a target Node or querySelector inside a document
## Description
`ConnectionObserver` is a tiny (1kb) API that provides a way to asynchronously observe the connectedness of a target Node or querySelector inside a document.
With `ConnectionObserver`, you have a low-level building block that can be used to build functionality on top of when you need to
perform work when a Node lives inside the DOM, and/or perform work when it becomes detached.### Features
- Familiar API: Follows the same conventions as [`MutationObserver`](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver), [`IntersectionObserver`](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API), [`PerformanceObserver`](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceObserver), and [`ResizeObserver`](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver)
- Asynchronous: Entries are batched together as microtasks
- Tiny (1kb)
- Performant## Table of Contents
- [Description](#description)
- [Features](#features)
- [Table of Contents](#table-of-contents)
- [Install](#install)
- [npm](#npm)
- [Yarn](#yarn)
- [pnpm](#pnpm)
- [Usage](#usage)
- [Constructing a ConnectionObserver](#constructing-a-connectionobserver)
- [Observing Nodes for connectedness](#observing-nodes-for-connectedness)
- [Observing querySelectors for connectedness](#observing-queryselectors-for-connectedness)
- [Disconnecting the ConnectionObserver](#disconnecting-the-connectionobserver)
- [Taking ConnectionRecords immediately](#taking-connectionrecords-immediately)
- [API reference](#api-reference)
- [ConnectionObserver](#connectionobserver)
- [ConnectionCallback](#connectioncallback)
- [ConnectionRecord](#connectionrecord)
- [Contributing](#contributing)
- [Maintainers](#maintainers)
- [Backers](#backers)
- [Patreon](#patreon)
- [FAQ](#faq)
- [Why can't you just use MutationObservers for this](#why-cant-you-just-use-mutationobservers-for-this)
- [Why wouldn't you use MutationEvents for this](#why-wouldnt-you-use-mutationevents-for-this)
- [License](#license)## Install
### npm
```
$ npm install @wessberg/connection-observer
```### Yarn
```
$ yarn add @wessberg/connection-observer
```### pnpm
```
$ pnpm add @wessberg/connection-observer
```## Usage
If you are familiar with the family of observers such as `MutationObserver` and `IntersectionObserver`, you will feel right at home
with `ConnectionObserver`. Not only is the API very similar, it is also asynchronous and batches together records on the microtask queue.```typescript
import {ConnectionObserver} from "@wessberg/connection-observer";// Hook up a new ConnectionObserver
const observer = new ConnectionObserver(entries => {
// For each entry, print the connection state as well as the target node to the console
for (const {connected, target} of entries) {
console.log("target:", target);
console.log("connected:", connected);
}
});// Observe 'someElement' for connectedness
observer.observe(someElement);// Eventually disconnect the observer when you are done observing elements for connectedness
observer.disconnect();
```### Constructing a ConnectionObserver
The `ConnectionObserver` constructor creates and returns a new observer which invokes a specified callback when there are new connectedness entries available.
If you don't call provide any Nodes to the `observe` method on the `ConnectionObserver` instance, the callback will never be called since no Nodes will be observed for connectedness.```typescript
const connectionObserver = new ConnectionObserver(callback);
```### Observing Nodes for connectedness
The `ConnectionObserver` method `observe` configures the `ConnectionObserver` callback to begin receiving notifications of changes to the connectedness of the given Node(s).
The callback will be invoked immediately with the connectedness of the observed Node(s).```typescript
connectionObserver.observe(target);
```### Observing querySelectors for connectedness
The `ConnectionObserver` method `observe` also accepts a query selector as the first argument, instead of a specific Node. This enables you to subscribe to connectedness events
for any Nodes that matches your querySelector inside of the document, including any Shadow roots. You can use this functionality for performing actions on elements matching your
querySelector as they enter and leave the DOM. For example:```typescript
const connectionObserver = new ConnectionObserver(entries => {
for (const {connected, target} of entries) {
if (connected) {
makeImageFancy(target);
}
}
});
connectionObserver.observe(`img[data-fancy]`);
```### Disconnecting the ConnectionObserver
The `ConnectionObserver` method `disconnect` will stop watching for the connectedness of all observed Nodes such that the callback won't be triggered any longer.
```typescript
connectionObserver.disconnect();
```### Taking ConnectionRecords immediately
`ConnectionObserver` is asynchronous which means that `ConnectionEntries` will be batched together and be provided to the callback given in the constructor (see [this section](#constructing-a-connectionobserver)) as a microtask.
The method `takeRecords` returns the entries that are currently queued in the batch and haven't been processed yet, leaving the connection queue empty. This may be useful if you want to immediately fetch all pending connection records immediately before disconnecting the observer, so that any pending changes can be processed.```typescript
const entries = connectionObserver.takeRecords();
```## API reference
This section includes a more code-oriented introduction to the types and interfaces of `ConnectionObserver`
### ConnectionObserver
```typescript
class ConnectionObserver {
[Symbol.toStringTag]: string;/**
* Constructs a new ConnectionObserver
* @param {ConnectionCallback} callback
*/
constructor(callback: ConnectionCallback);/**
* Observe the given node or query selector for connections/disconnections.
* If given a Node, that specific Node will be observed. If given a query selector, such
* as for example "img[data-some-attr]", for each new MutationRecord, the query selector
* will be executed and the matched nodes will be observed for connections/disconnections
* @param {string} target
* @example {observe("img[data-some-attr]")}
*/
observe(target: Node | string): void;/**
* Takes the records immediately (instead of waiting for the next flush)
* @return {ConnectionRecord[]}
*/
takeRecords(): ConnectionRecord[];/**
* Disconnects the ConnectionObserver such that none of its callbacks will be invoked any longer
*/
disconnect(): void;
}
```### ConnectionCallback
A `ConnectionCallback` must be provided to the constructor of [`ConnectionObserver`](#connectionobserver) and will be invoked when
there are new [ConnectionRecords](#connectionrecord) available.```typescript
type ConnectionCallback = (entries: ConnectionRecord[], observer: IConnectionObserver) => void;
```### ConnectionRecord
[ConnectionCallbacks](#connectioncallback) are invoked with an array of `ConnectionRecord`s. Those have the following members:
```typescript
interface ConnectionRecord {
/**
* Whether or not the node is Connected
*/
readonly connected: boolean;/**
* The target Node
*/
readonly target: Node;
}
```## Contributing
Do you want to contribute? Awesome! Please follow [these recommendations](./CONTRIBUTING.md).
## Maintainers
|
|
| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [Frederik Wessberg](mailto:frederikwessberg@hotmail.com)
Twitter: [@FredWessberg](https://twitter.com/FredWessberg)
Github: [@wessberg](https://github.com/wessberg)
_Lead Developer_ |## Backers
|
|
|
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [Bubbles](https://usebubbles.com)
Twitter: [@use_bubbles](https://twitter.com/use_bubbles) | [Christopher Blanchard](https://github.com/cblanc) |### Patreon
## FAQ
#### Why can't you just use MutationObservers for this
With [`MutationObserver`](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver), we can watch for changes being made to the DOM tree from any root,
but using it to watch for when an arbitrary Node is attached to or detached from the DOM is very hard since that requires tracking all [Shadow Roots](https://developer.mozilla.org/en-US/docs/Web/API/ShadowRoot).There is [an ongoing discussion](https://github.com/whatwg/dom/issues/533) about adding support for tracking connectedness of any Node via MutationObservers, and this library aims to render itself obsolete if and when
that becomes a reality in favor of a polyfill.#### Why wouldn't you use MutationEvents for this
[MutationEvents](https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Mutation_events) are deprecated and I would discourage you from using them.
Additionally, these were designed and implemented in browser before Shadow DOM v1 came to be, and they are somewhat unreliable for tracking the connectedness of Nodes inside of Shadow roots.
Additionally, they are synchronous which is bad for performance and has proven to be performance-killers in numerous benchmarks and investigations.## License
MIT © [Frederik Wessberg](mailto:frederikwessberg@hotmail.com) ([@FredWessberg](https://twitter.com/FredWessberg)) ([Website](https://github.com/wessberg))