Title: Intersection Observer
Status: ED
ED: https://w3c.github.io/IntersectionObserver/
Shortname: intersection-observer
TR: https://www.w3.org/TR/intersection-observer/
Previous version: from biblio
Level: none
Editor: Stefan Zager, Google, szager@google.com, w3cid 91208
Editor: Emilio Cobos Álvarez , Mozilla, emilio@mozilla.com, w3cid 106537
Editor: Traian Captan, Google, tcaptan@google.com, w3cid 137959
Former Editor: Michael Blain, Google, mpb@google.com, w3cid 73819
Abstract: This specification describes an API that can be used to understand the visibility and position of DOM elements ("targets") relative to a containing element or to the top-level viewport ("root"). The position is delivered asynchronously and is useful for understanding the visibility of elements and implementing pre-loading and deferred loading of DOM content.
Group: webapps
Repository: W3C/IntersectionObserver
Test Suite: http://w3c-test.org/intersection-observer/
Ignored Vars: rootMargin, docs, now
Markup Shorthands: markdown yes
urlPrefix: https://dom.spec.whatwg.org/
	url: #node-trees; type: dfn; text: node tree
urlPrefix: http://www.w3.org/TR/hr-time/
	type: typedef; text: DOMHighResTimeStamp
	type: dfn; text: time origin
urlPrefix: https://html.spec.whatwg.org/multipage/
	urlPrefix: dom.html
		url: #document; type:dfn; text: Document
	urlPrefix: browsers.html
		type: dfn; text: browsing context
		type: dfn; text: top-level browsing context
		type: dfn; text: nested browsing context
		type: dfn; text: list of the descendant browsing contexts
		type: dfn; text: browsing context container
		type: dfn; text: fully active
	urlPrefix: webappapis.html;
		type: dfn; text: report the exception
		type: dfn; text: event loop
		type: dfn; text: queue a task
		type: dfn; text: run the fullscreen rendering steps
		type: dfn; text: run the animation frame callbacks
		url: #event-loop-processing-model; type: dfn; text: HTML Event Loops Processing Model
		type: dfn; text: relevant settings object
		url: #concept-environment-top-level-origin; type: dfn; text: top-level origin
	urlPrefix: infrastructure.html;
		url: #dfn-callback-this-value; type: dfn; text: callback this value
	urlPrefix: origin.html
		type: dfn; text: origin
urlPrefix: https://heycam.github.io/webidl/
	url: #dfn-simple-exception; type:exception;
		text: RangeError
		text: TypeError
		text: SyntaxError
	urlPrefix: #dfn-; type:dfn; text: throw
	urlPrefix: #idl-; type:interface; text: double
	urlPrefix: #idl-; type:interface; text: undefined
	url: #hierarchyrequesterror; type: exception; text: HierarchyRequestError
urlPrefix: https://drafts.csswg.org/css-box/
	url: #containing-block; type: dfn; text: containing block
	url: #padding-area; type: dfn; text: padding area
	url: #padding-edge; type: dfn; text: padding edge
urlPrefix: https://drafts.csswg.org/css-display/
	url: #containing-block-chain; type: dfn; text: containing block chain
urlPrefix: http://www.w3.org/TR/css-masking-1/
	url: #propdef-clip-path; type:dfn; text: clip-path
urlPrefix: https://drafts.csswg.org/css-overflow-3/
	url: #ink-overflow-rectangle; type:dfn; text: ink overflow rectangle
	url: #ink-overflow-region; type:dfn; text: ink overflow region
	url: #overflow-properties; type:dfn; text: overflow properties
urlPrefix: https://drafts.csswg.org/css-transforms-1/
	url: #transformation-matrix; type:dfn; text: transformation matrix
	url: #serialization-of-the-computed-value; type:dfn; text: serialization
	url: #identity-transform-function; type:dfn; text: identity transform function
	url: #post-multiplied; type:dfn; text: post-multiplied
urlPrefix: https://drafts.csswg.org/cssom-view-1/
	url: #pinch-zoom; type:dfn; text: pinch zoom
urlPrefix: https://drafts.csswg.org/css2/visuren.html
	url: #viewport; type:dfn; text: viewport
urlPrefix: https://drafts.fxtf.org/filter-effects/
	url: #funcdef-filter-blur; type:dfn; text: blur

Introduction

The web's traditional position calculation mechanisms rely on explicit queries of DOM state that are known to cause (expensive) style recalculation and layout and, frequently, are a source of significant performance overhead due to continuous polling for this information. A body of common practice has evolved that relies on these behaviors, however, including (but not limited to): * Building custom pre- and deferred-loading of DOM and data. * Implementing data-bound high-performance scrolling lists which load and render subsets of data sets. These lists are a central mobile interaction idiom. * Calculating element visibility. In particular, ad networks now require reporting of ad "visibility" for monetizing impressions. This has led to many sites abusing scroll handlers (causing jank on scroll), synchronous layout invoking readbacks (causing unnecessary critical work in rAF loops), and resorting to exotic plugin-based solutions for computing "true" element visibility (with all the associated overhead of the plugin architecture). These use-cases have several common properties: 1. They can be represented as passive "queries" about the state of individual elements with respect to some other element (or the global viewport). 2. They do not impose hard latency requirements; that is to say, the information can be delivered asynchronously (e.g. from another thread) without penalty. 3. They are poorly supported by nearly all combinations of existing web platform features, requiring extraordinary developer effort despite their widespread use. A notable non-goal is pixel-accurate information about what was actually displayed (which can be quite difficult to obtain efficiently in certain browser architectures in the face of filters, webgl, and other features). In all of these scenarios the information is useful even when delivered at a slight delay and without perfect compositing-result data. The Intersection Observer API addresses the above issues by giving developers a new method to asynchronously query the position of an element with respect to other elements or the global viewport. The asynchronous delivery eliminates the need for costly DOM and style queries, continuous polling, and use of custom plugins. By removing the need for these methods it allows applications to significantly reduce their CPU, GPU and energy costs.
	var observer = new IntersectionObserver(changes => {
		for (const change of changes) {
			console.log(change.time);               // Timestamp when the change occurred
			console.log(change.rootBounds);         // Unclipped area of root
			console.log(change.boundingClientRect); // target.getBoundingClientRect()
			console.log(change.intersectionRect);   // boundingClientRect, clipped by its containing block ancestors, and intersected with rootBounds
			console.log(change.intersectionRatio);  // Ratio of intersectionRect area to boundingClientRect area
			console.log(change.target);             // the Element target
		}
	}, {});

	// Watch for intersection events on a specific target Element.
	observer.observe(target);

	// Stop watching for intersection events on a specific target Element.
	observer.unobserve(target);

	// Stop observing threshold events on all target elements.
	observer.disconnect();
	

Intersection Observer

The Intersection Observer API enables developers to understand the visibility and position of target DOM elements relative to an intersection root.

The IntersectionObserverCallback

	callback IntersectionObserverCallback = undefined (sequence<IntersectionObserverEntry> entries, IntersectionObserver observer);
This callback will be invoked when there are changes to a target's intersection with the intersection root, as per the processing model.

The IntersectionObserver interface

The {{IntersectionObserver}} interface can be used to observe changes in the intersection of an intersection root and one or more target {{Element}}s. The intersection root for an {{IntersectionObserver}} is the value of its {{IntersectionObserver/root}} attribute if the attribute is non-null; otherwise, it is the top-level browsing context's {{document}} node, referred to as the implicit root. An {{IntersectionObserver}} with a non-null {{IntersectionObserver/root}} is referred to as an explicit root observer, and it can observe any target {{Element}} that is a descendant of the {{IntersectionObserver/root}} in the containing block chain. An {{IntersectionObserver}} with a null {{IntersectionObserver/root}} is referred to as an implicit root observer. Valid targets for an implicit root observer include any {{Element}} in the top-level browsing context, as well as any {{Element}} in any nested browsing context which is in the list of the descendant browsing contexts of the top-level browsing context. When dealing with implicit root observers, the API makes a distinction between a target whose relevant settings object's origin is same origin-domain with the top-level origin, referred to as a same-origin-domain target; as opposed to a cross-origin-domain target. Any target of an explicit root observer is also a same-origin-domain target, since the target must be in the same document as the intersection root. Note: In {{MutationObserver}}, the {{MutationObserverInit}} options are passed to {{MutationObserver/observe()}} while in {{IntersectionObserver}} they are passed to the constructor. This is because for MutationObserver, each {{Node}} being observed could have a different set of attributes to filter for. For {{IntersectionObserver}}, developers may choose to use a single observer to track multiple targets using the same set of options; or they may use a different observer for each tracked target. {{IntersectionObserverInit/rootMargin}} or {{threshold}} values for each target seems to introduce more complexity without solving additional use-cases. Per-{{observe()}} options could be provided in the future if the need arises.
[Exposed=Window]
interface IntersectionObserver {
	constructor(IntersectionObserverCallback callback, optional IntersectionObserverInit options = {});
	readonly attribute (Element or Document)? root;
	readonly attribute DOMString rootMargin;
	readonly attribute DOMString scrollMargin;
	readonly attribute FrozenArray<double> thresholds;
	readonly attribute long delay;
	readonly attribute boolean trackVisibility;
	undefined observe(Element target);
	undefined unobserve(Element target);
	undefined disconnect();
	sequence<IntersectionObserverEntry> takeRecords();
};
: new IntersectionObserver(callback, options) :: Return the result of running the initialize a new IntersectionObserver algorithm, providing |callback| and |options|. : observe(target) :: Run the observe a target Element algorithm, providing |this| and |target|. : unobserve(target) :: Run the unobserve a target Element algorithm, providing |this| and |target|. Note: {{MutationObserver}} does not implement {{unobserve()}}. For {{IntersectionObserver}}, {{unobserve()}} addresses the lazy-loading use case. After loading is initiated for |target|, it does not need to be tracked. It would be more work to either {{disconnect()}} all |target|s and {{observe()}} the remaining ones, or create a separate {{IntersectionObserver}} for each |target|. : disconnect() :: For each |target| in |this|'s internal {{[[ObservationTargets]]}} slot: 1. Remove the {{IntersectionObserverRegistration}} record whose {{IntersectionObserverRegistration/observer}} property is equal to |this| from |target|'s internal {{[[RegisteredIntersectionObservers]]}} slot. 2. Remove |target| from |this|'s internal {{[[ObservationTargets]]}} slot. : takeRecords() :: 1. Let |queue| be a copy of |this|'s internal {{[[QueuedEntries]]}} slot. 2. Clear |this|'s internal {{[[QueuedEntries]]}} slot. 3. Return |queue|.
: root :: The {{IntersectionObserverInit/root}} provided to the {{IntersectionObserver}} constructor, or null if none was provided. : rootMargin :: Offsets applied to the root intersection rectangle, effectively growing or shrinking the box that is used to calculate intersections. These offsets are only applied when handling same-origin-domain targets; for cross-origin-domain targets they are ignored. On getting, return the result of serializing the elements of {{[[rootMargin]]}} space-separated, where pixel lengths serialize as the numeric value followed by "px", and percentages serialize as the numeric value followed by "%". Note that this is not guaranteed to be identical to the |options|.{{IntersectionObserverInit/rootMargin}} passed to the {{IntersectionObserver}} constructor. If no {{IntersectionObserverInit/rootMargin}} was passed to the {{IntersectionObserver}} constructor, the value of this attribute is "0px 0px 0px 0px". : scrollMargin :: Offsets are applied to scrollports on the path from intersection root to target, effectively growing or shrinking the clip rects used to calculate intersections. On getting, return the result of serializing the elements of {{[[scrollMargin]]}} space-separated, where pixel lengths serialize as the numeric value followed by "px", and percentages serialize as the numeric value followed by "%". Note that this is not guaranteed to be identical to the |options|.{{IntersectionObserverInit/scrollMargin}} passed to the {{IntersectionObserver}} constructor. If no {{IntersectionObserverInit/scrollMargin}} was passed to the {{IntersectionObserver}} constructor, the value of this attribute is "0px 0px 0px 0px". : thresholds :: A list of thresholds, sorted in increasing numeric order, where each threshold is a ratio of intersection area to bounding box area of an observed target. Notifications for a target are generated when any of the thresholds are crossed for that target. If no |options|.{{IntersectionObserverInit/threshold}} was provided to the {{IntersectionObserver}} constructor, or the sequence is empty, the value of this attribute will be [0]. : delay :: A number indicating the minimum delay in milliseconds between notifications from this observer for a given target. : trackVisibility :: A boolean indicating whether this {{IntersectionObserver}} will track changes in a target's visibility.
An {{Element}} is defined as having a content clip if its computed style has overflow properties that cause its content to be clipped to the element's padding edge. The root intersection rectangle for an {{IntersectionObserver}} is the rectangle we'll use to check against the targets.
If the {{IntersectionObserver}} is an implicit root observer,
it's treated as if the root were the top-level browsing context's {{document}}, according to the following rule for {{document}}.
If the intersection root is a {{document}},
it's the size of the {{document}}'s viewport (note that this processing step can only be reached if the {{document}} is fully active).
Otherwise, if the intersection root has a content clip,
it's the element's padding area.
Otherwise,
it's the result of getting the bounding box for the intersection root.
When calculating the root intersection rectangle for a same-origin-domain target, the rectangle is then expanded according to the offsets in the {{IntersectionObserver}}’s {{[[rootMargin]]}} slot in a manner similar to CSS's 'margin' property, with the four values indicating the amount the top, right, bottom, and left edges, respectively, are offset by, with positive lengths indicating an outward offset. Percentages are resolved relative to the width of the undilated rectangle. Note: {{IntersectionObserver/rootMargin}} only applies to the intersection root itself. If a target {{Element}} is clipped by an ancestor other than the intersection root, that clipping is unaffected by {{IntersectionObserver/rootMargin}}. : To apply scroll margin to a scrollport :: When calculating a scrollport intersection rectangle for a same-origin-domain target, the rectangle is expanded according to the offsets in the {{IntersectionObserver}}’s {{[[scrollMargin]]}} slot in a manner similar to CSS's 'margin' property, with the four values indicating the amount the top, right, bottom, and left edges, respectively, are offset by, with positive lengths indicating an outward offset. Percentages are resolved relative to the width of the undilated rectangle. These offsets are only applied when handling same-origin-domain targets; for cross-origin-domain targets they are ignored. Note: {{IntersectionObserver/scrollMargin}} affects the clipping of target by all scrollable ancestors up to and including the intersection root. Both the {{IntersectionObserver/scrollMargin}} and the {{IntersectionObserver/rootMargin}} are applied to a scrollable intersection root's rectangle. Note: Root intersection rectangle and scrollport intersection rectangles are not affected by pinch zoom and will report the unadjusted viewport, consistent with the intent of pinch zooming (to act like a magnifying glass and NOT change layout.) To parse a margin (root or scroll) from an input string |marginString|, returning either a list of 4 pixel lengths or percentages, or failure: 1. Parse a list of component values |marginString|, storing the result as |tokens|. 2. Remove all whitespace tokens from |tokens|. 3. If the length of |tokens| is greater than 4, return failure. 4. If there are zero elements in |tokens|, set |tokens| to ["0px"]. 5. Replace each |token| in |tokens|: * If |token| is an absolute length dimension token, replace it with a an equivalent pixel length. * If |token| is a <> token, replace it with an equivalent percentage. * Otherwise, return failure. 6. If there is one element in |tokens|, append three duplicates of that element to |tokens|. Otherwise, if there are two elements are |tokens|, append a duplicate of each element to |tokens|. Otherwise, if there are three elements in |tokens|, append a duplicate of the second element to |tokens|. 7. Return |tokens|.

The IntersectionObserverEntry interface

[Exposed=Window]
interface IntersectionObserverEntry {
	constructor(IntersectionObserverEntryInit intersectionObserverEntryInit);
	readonly attribute DOMHighResTimeStamp time;
	readonly attribute DOMRectReadOnly? rootBounds;
	readonly attribute DOMRectReadOnly boundingClientRect;
	readonly attribute DOMRectReadOnly intersectionRect;
	readonly attribute boolean isIntersecting;
	readonly attribute boolean isVisible;
	readonly attribute double intersectionRatio;
	readonly attribute Element target;
};

dictionary IntersectionObserverEntryInit {
	required DOMHighResTimeStamp time;
	required DOMRectInit? rootBounds;
	required DOMRectInit boundingClientRect;
	required DOMRectInit intersectionRect;
	required boolean isIntersecting;
	required boolean isVisible;
	required double intersectionRatio;
	required Element target;
};
: boundingClientRect :: A {{DOMRectReadOnly}} obtained by getting the bounding box for {{IntersectionObserverEntry/target}}. : intersectionRect :: {{IntersectionObserverEntry/boundingClientRect}}, intersected by each of {{IntersectionObserverEntry/target}}'s ancestors' clip rects (up to but not including {{IntersectionObserver/root}}), intersected with the root intersection rectangle. This value represents the portion of {{IntersectionObserverEntry/target}} that intersects with the root intersection rectangle. : isIntersecting :: True if the {{IntersectionObserverEntry/target}} intersects with the {{IntersectionObserver/root}}; false otherwise. This flag makes it possible to distinguish between an {{IntersectionObserverEntry}} signalling the transition from intersecting to not-intersecting; and an {{IntersectionObserverEntry}} signalling a transition from not-intersecting to intersecting with a zero-area intersection rect (as will happen with edge-adjacent intersections, or when the {{IntersectionObserverEntry/boundingClientRect}} has zero area). : isVisible :: Contains the result of running the visibility algorithm on {{IntersectionObserverEntry/target}}. : intersectionRatio :: If the {{IntersectionObserverEntry/boundingClientRect}} has non-zero area, this will be the ratio of {{IntersectionObserverEntry/intersectionRect}} area to {{IntersectionObserverEntry/boundingClientRect}} area. Otherwise, this will be 1 if the {{IntersectionObserverEntry/isIntersecting}} is true, and 0 if not. : rootBounds :: For a same-origin-domain target, this will be the root intersection rectangle. Otherwise, this will be null. Note that if the target is in a different browsing context than the intersection root, this will be in a different coordinate system than {{IntersectionObserverEntry/boundingClientRect}} and {{IntersectionObserverEntry/intersectionRect}}. : target :: The {{Element}} whose intersection with the intersection root changed. : time :: The attribute must return a {{DOMHighResTimeStamp}} that corresponds to the time the intersection was recorded, relative to the time origin of the global object associated with the IntersectionObserver instance that generated the notification.

The IntersectionObserverInit dictionary

dictionary IntersectionObserverInit {
	(Element or Document)?  root = null;
	DOMString rootMargin = "0px";
	DOMString scrollMargin = "0px";
	(double or sequence<double>) threshold = 0;
	long delay = 0;
	boolean trackVisibility = false;
};
: root :: The {{IntersectionObserver|root}} to use for intersection. If not provided, use the implicit root. : rootMargin :: Similar to the CSS 'margin' property, this is a string of 1-4 components, each either an absolute length or a percentage.
			"5px"                // all margins set to 5px
			"5px 10px"           // top & bottom = 5px, right & left = 10px
			"-10px 5px 8px"      // top = -10px, right & left = 5px, bottom = 8px
			"-10px -5px 5px 8px" // top = -10px, right = -5px, bottom = 5px, left = 8px
		
: scrollMargin :: Similar to {{IntersectionObserverInit/rootMargin}}, this is a string of 1-4 components, each either an absolute length or a percentage. See {{IntersectionObserverInit/rootMargin}} above for the example. : threshold :: List of threshold(s) at which to trigger callback. callback will be invoked when intersectionRect's area changes from greater than or equal to any threshold to less than that threshold, and vice versa. Threshold values must be in the range of [0, 1.0] and represent a percentage of the area of the rectangle produced by getting the bounding box for target. Note: 0.0 is effectively "any non-zero number of pixels". : delay :: A number specifying the minimum delay in milliseconds between notifications from the observer for a given target. : trackVisibility :: A boolean indicating whether the observer should track visibility. Note that tracking visibility is likely to be a more expensive operation than tracking intersections. It is recommended that this option be used only when necessary.

Processing Model

This section outlines the steps the user agent must take when implementing the Intersection Observer API.

Internal Slot Definitions

Document

Each {{document}} has an IntersectionObserverTaskQueued flag which is initialized to false.

Element

{{Element}} objects have an internal \[[RegisteredIntersectionObservers]] slot, which is initialized to an empty list. This list holds IntersectionObserverRegistration records, which have: * an observer property holding an {{IntersectionObserver}}. * a previousThresholdIndex property holding a number between -1 and the length of the observer's {{IntersectionObserver/thresholds}} property (inclusive). * a previousIsIntersecting property holding a boolean. * a lastUpdateTime property holding a {{DOMHighResTimeStamp}} value. * a previousIsVisible property holding a boolean.

IntersectionObserver

{{IntersectionObserver}} objects have the following internal slots: * A \[[QueuedEntries]] slot initialized to an empty list. * A \[[ObservationTargets]] slot initialized to an empty list. * A \[[callback]] slot which is initialized by {{IntersectionObserver(callback, options)}}. * A \[[rootMargin]] slot which is a list of four pixel lengths or percentages. * A \[[scrollMargin]] slot which is a list of four pixel lengths or percentages. * A \[[thresholds]] slot which is initialized by {{IntersectionObserver(callback, options)}}. * A \[[delay]] slot which is initialized by {{IntersectionObserver(callback, options)}}. * A \[[trackVisibility]] slot which is initialized by {{IntersectionObserver(callback, options)}}.

Algorithms

Initialize a new IntersectionObserver

To initialize a new IntersectionObserver, given an {{IntersectionObserverCallback}} |callback| and an {{IntersectionObserverInit}} dictionary |options|, run these steps: 1. Let |this| be a new {{IntersectionObserver}} object 2. Set |this|'s internal {{[[callback]]}} slot to |callback|. 3. Attempt to parse a margin from |options|.{{IntersectionObserverInit/rootMargin}}. If a list is returned, set |this|'s internal {{[[rootMargin]]}} slot to that. Otherwise, throw a {{SyntaxError}} exception. 4. Attempt to parse a margin from |options|.{{IntersectionObserverInit/scrollMargin}}. If a list is returned, set |this|'s internal {{[[scrollMargin]]}} slot to that. Otherwise, throw a {{SyntaxError}} exception. 5. Let |thresholds| be a list equal to |options|.{{IntersectionObserverInit/threshold}}. 6. If any value in |thresholds| is less than 0.0 or greater than 1.0, throw a {{RangeError}} exception. 7. Sort |thresholds| in ascending order. 8. If |thresholds| is empty, append 0 to |thresholds|. 9. The {{IntersectionObserver/thresholds}} attribute getter will return this sorted |thresholds| list. 10. Let |delay| be the value of |options|.{{IntersectionObserverInit/delay}}. 11. If |options|.{{IntersectionObserverInit/trackVisibility}} is true and |delay| is less than 100, set |delay| to 100. 11. Set |this|'s internal {{[[delay]]}} slot to |options|.{{IntersectionObserverInit/delay}} to |delay|. 12. Set |this|'s internal {{[[trackVisibility]]}} slot to |options|.{{IntersectionObserverInit/trackVisibility}}. 13. Return |this|.

Observe a target Element

To observe a target Element, given an {{IntersectionObserver}} |observer| and an {{Element}} |target|, follow these steps: 1. If |target| is in |observer|'s internal {{[[ObservationTargets]]}} slot, return. 2. Let |intersectionObserverRegistration| be an {{IntersectionObserverRegistration}} record with an {{IntersectionObserverRegistration/observer}} property set to |observer|, a {{IntersectionObserverRegistration/previousThresholdIndex}} property set to -1, a {{IntersectionObserverRegistration/previousIsIntersecting}} property set to false, and a {{IntersectionObserverRegistration/previousIsVisible}} property set to false. 3. Append |intersectionObserverRegistration| to |target|'s internal {{[[RegisteredIntersectionObservers]]}} slot. 4. Add |target| to |observer|'s internal {{[[ObservationTargets]]}} slot.

Unobserve a target Element

To unobserve a target Element, given an {{IntersectionObserver}} |observer| and an {{Element}} |target|, follow these steps: 1. Remove the {{IntersectionObserverRegistration}} record whose {{IntersectionObserverRegistration/observer}} property is equal to |this| from |target|'s internal {{[[RegisteredIntersectionObservers]]}} slot, if present. 2. Remove |target| from |this|'s internal {{[[ObservationTargets]]}} slot, if present

Queue an Intersection Observer Task

The IntersectionObserver task source is a [=task source=] used for scheduling tasks to [[#notify-intersection-observers-algo]]. To queue an intersection observer task for a {{document}} |document|, run these steps: 1. If |document|'s IntersectionObserverTaskQueued flag is set to true, return. 2. Set |document|'s IntersectionObserverTaskQueued flag to true. 3. Queue a task on the IntersectionObserver task source associated with the {{document}}'s event loop to notify intersection observers.

Notify Intersection Observers

To notify intersection observers for a {{document}} |document|, run these steps: 1. Set |document|'s IntersectionObserverTaskQueued flag to false. 2. Let |notify list| be a list of all {{IntersectionObserver}}s whose {{IntersectionObserver/root}} is in the DOM tree of |document|. 3. For each {{IntersectionObserver}} object |observer| in |notify list|, run these steps: 1. If |observer|'s internal {{[[QueuedEntries]]}} slot is empty, continue. 2. Let |queue| be a copy of |observer|'s internal {{[[QueuedEntries]]}} slot. 3. Clear |observer|'s internal {{[[QueuedEntries]]}} slot. 4. Let |callback| be the value of |observer|'s internal {{[[callback]]}} slot. 5. Invoke |callback| with |queue| as the first argument, |observer| as the second argument, and |observer| as the callback this value. If this throws an exception, report the exception.

Queue an IntersectionObserverEntry

To queue an IntersectionObserverEntry for an {{IntersectionObserver}} |observer|, given a {{document}} |document|; {{DOMHighResTimeStamp}} |time|; {{DOMRect}}s |rootBounds|, |boundingClientRect|, |intersectionRect|, and |isIntersecting| flag; and an {{Element}} |target|; run these steps: 1. Construct an {{IntersectionObserverEntry}}, passing in |time|, |rootBounds|, |boundingClientRect|, |intersectionRect|, |isIntersecting|, and |target|. 2. Append it to |observer|'s internal {{[[QueuedEntries]]}} slot. 3. Queue an intersection observer task for |document|.

Compute the Intersection of a Target Element and the Root

To compute the intersection between a target |target| and an intersection root |root|, run these steps: 1. Let |intersectionRect| be the result of getting the bounding box for |target|. 2. Let |container| be the containing block of |target|. 3. While |container| is not |root|: 1. If |container| is the {{document}} of a nested browsing context, update |intersectionRect| by clipping to the viewport of the {{document}}, and update |container| to be the browsing context container of |container|. 2. Map |intersectionRect| to the coordinate space of |container|. 3. If |container| is a scroll container, apply the {{IntersectionObserver}}’s {{[[scrollMargin]]}} to the |container|'s clip rect as described in apply scroll margin to a scrollport. 4. If |container| has a content clip or a css clip-path property, update |intersectionRect| by applying |container|'s clip. 5. If |container| is the root element of a browsing context, update |container| to be the browsing context's {{document}}; otherwise, update |container| to be the containing block of |container|. 4. Map |intersectionRect| to the coordinate space of |root|. 5. Update |intersectionRect| by intersecting it with the root intersection rectangle. 6. Map |intersectionRect| to the coordinate space of the viewport of the {{document}} containing |target|. 7. Return |intersectionRect|.

Compute whether a Target is unoccluded, untransformed, unfiltered, and opaque.

To compute the visibility of a target, run these steps: 1. If the |observer|'s {{IntersectionObserver/trackVisibility}} attribute is false, return false. 2. If the target has an effective transformation matrix other than a 2D translation or proportional 2D upscaling, return false. 3. If the target, or any element in its containing block chain, has an effective opacity other than 100%, return false. 4. If the target, or any element in its containing block chain, has any filters applied, return false. 5. If the implementation cannot guarantee that the target is completely unoccluded by other page content, return false. Note: Implementations should use the ink overflow rectangle of page content when determining whether a target is occluded. For blur effects, which have theoretically infinite extent, the ink overflow rectangle is defined by the finite-area approximation described for the blur filter function. 6. Return true.

Calculate a target's Effective Transformation Matrix

To compute the effective transformation matrix of a target, run these steps: 1. Let |matrix| be the serialization of the identity transform function. 2. Let |container| be the target. 3. While |container| is not the intersection root: 1. Set |t| to |container|'s transformation matrix. 2. Set |matrix| to |t| post-multiplied by |matrix|. 3. If |container| is the root element of a nested browsing context, update |container| to be the browsing context container of |container|. Otherwise, update |container| to be the containing block of |container|. 4. Return |matrix|.

Run the Update Intersection Observations Steps

To run the update intersection observations steps for a Document |document| given a timestamp |time|, run these steps: 1. Let |observer list| be a list of all {{IntersectionObserver}}s whose {{IntersectionObserver/root}} is in the DOM tree of |document|. For the top-level browsing context, this includes implicit root observers. 2. For each |observer| in |observer list|: 1. Let |rootBounds| be |observer|'s root intersection rectangle. 2. For each |target| in |observer|'s internal {{[[ObservationTargets]]}} slot, processed in the same order that {{observe()}} was called on each |target|: 1. Let |registration| be the {{IntersectionObserverRegistration}} record in |target|'s internal {{[[RegisteredIntersectionObservers]]}} slot whose {{IntersectionObserverRegistration/observer}} property is equal to |observer|. 2. If (|time| - |registration|.{{IntersectionObserverRegistration/lastUpdateTime}} < |observer|.{{IntersectionObserver/delay}}), skip further processing for |target|. 3. Set |registration|.{{IntersectionObserverRegistration/lastUpdateTime}} to |time|. 4. Let: - |thresholdIndex| be 0. - |isIntersecting| be false. - |targetRect| be a {{DOMRectReadOnly}} with |x|, |y|, |width|, and |height| set to 0. - |intersectionRect| be a {{DOMRectReadOnly}} with |x|, |y|, |width|, and |height| set to 0. 5. If the intersection root is not the implicit root, and |target| is not in the same {{document}} as the intersection root, skip to step 11. 6. If the intersection root is an {{Element}}, and |target| is not a descendant of the intersection root in the containing block chain, skip to step 11. 7. Set |targetRect| to the {{DOMRectReadOnly}} obtained by getting the bounding box for |target|. 8. Let |intersectionRect| be the result of running the compute the intersection algorithm on |target| and |observer|'s intersection root. 9. Let |targetArea| be |targetRect|'s area. 10. Let |intersectionArea| be |intersectionRect|'s area. 11. Let |isIntersecting| be true if |targetRect| and |rootBounds| intersect or are edge-adjacent, even if the intersection has zero area (because |rootBounds| or |targetRect| have zero area). 12. If |targetArea| is non-zero, let |intersectionRatio| be |intersectionArea| divided by |targetArea|.
Otherwise, let |intersectionRatio| be 1 if |isIntersecting| is true, or 0 if |isIntersecting| is false. 13. Set |thresholdIndex| to the index of the first entry in |observer|.{{thresholds}} whose value is greater than |intersectionRatio|, or the length of |observer|.{{thresholds}} if |intersectionRatio| is greater than or equal to the last entry in |observer|.{{thresholds}}. 14. Let |isVisible| be the result of running the visibility algorithm on |target|. 15. Let |previousThresholdIndex| be the |registration|'s {{IntersectionObserverRegistration/previousThresholdIndex}} property. 16. Let |previousIsIntersecting| be the |registration|'s {{IntersectionObserverRegistration/previousIsIntersecting}} property. 17. Let |previousIsVisible| be the |registration|'s {{IntersectionObserverRegistration/previousIsVisible}} property. 18. If |thresholdIndex| does not equal |previousThresholdIndex|, or if |isIntersecting| does not equal |previousIsIntersecting|, or if |isVisible| does not equal |previousIsVisible|, queue an IntersectionObserverEntry, passing in |observer|, |time|, |rootBounds|, |targetRect|, |intersectionRect|, |isIntersecting|, |isVisible|, and |target|. 19. Assign |thresholdIndex| to |registration|'s {{IntersectionObserverRegistration/previousThresholdIndex}} property. 20. Assign |isIntersecting| to |registration|'s {{IntersectionObserverRegistration/previousIsIntersecting}} property. 21. Assign |isVisible| to |registration|'s {{IntersectionObserverRegistration/previousIsVisible}} property.

IntersectionObserver Lifetime

An {{IntersectionObserver}} will remain alive until both of these conditions hold: An {{IntersectionObserver}} will continue observing a target until either the observer's {{IntersectionObserver/unobserve()}} method is called with the target as argument; or the observer's {{IntersectionObserver/disconnect()}} is called.

External Spec Integrations

HTML Processing Model: Event Loop

An Intersection Observer processing step exists as a substep within the "Update the rendering" step, in the HTML Event Loops Processing Model.

Pending initial IntersectionObserver targets

A {{document}} is said to have pending initial IntersectionObserver targets if there is at least one {{IntersectionObserver}} meeting these criteria:
  1. The |observer|'s {{IntersectionObserver|root}} is in the |document| (for the top-level browsing context, this includes implicit root observers).
  2. The |observer| has at least one |target| in its {{[[ObservationTargets]]}} slot for which no {{IntersectionObserverEntry}} has yet been queued.
In the HTML Event Loops Processing Model, under the "Update the rendering" step, the "Unnecessary rendering" step should be modified to add an additional requirement for skipping the rendering update:

Accessibility Considerations

*This section is non-normative.* There are no known accessibility considerations for the core IntersectionObserver specification (this document). There are, however, related specifications and proposals that leverage and refer to this spec, which might have their own accessibility considerations. In particular, specifications for [[html#lazy-loading-attributes]] and [[css-contain-2#content-visibility]] may have implications for [[html#find-in-page]], [[html#the-tabindex-attribute]], and spatial navigation.

Privacy and Security

*This section is non-normative.* The main privacy concerns associated with this API relate to the information it may provide to code running in the context of a cross-origin iframe (i.e., the cross-origin-domain target case). In particular: * There is no universal consensus on the privacy implications of revealing whether an iframe is within the global viewport. * There is a risk that the API may be used to probe for information about the geometry of the global viewport itself, which may be used to deduce the user's hardware configuration. The motivation for disabling the effects of {{IntersectionObserver/rootMargin}} and {{IntersectionObserver/scrollMargin}}, and suppressing {{IntersectionObserverEntry/rootBounds}} for cross-origin-domain targets is to prevent such probing. It should be noted that prior to {{IntersectionObserver}}, web developers used other API's in very ingenious (and grotesque) ways to tease out the information available from {{IntersectionObserver}}. As a purely practical matter, this API does not reveal any information that was not already available by other means. Another consideration is that {{IntersectionObserver}} uses {{DOMHighResTimeStamp}}, which has privacy and security considerations of its own. It is however unlikely that {{IntersectionObserver}} is vulnerable to timing-related exploits. Timestamps are generated at most once per rendering update (see [[#event-loop]]), which is far too infrequent for the familiar kind of timing attack.

Internationalization

*This section is non-normative.* There are no known issues concerning internationalization.

Acknowledgements

Special thanks to all the contributors for their technical input and suggestions that led to improvements to this specification.