forked from w3c/IntersectionObserver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.bs
794 lines (681 loc) · 37.2 KB
/
index.bs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
<pre class='metadata'>
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, [email protected], w3cid 91208
Editor: Emilio Cobos Álvarez , Mozilla, [email protected], w3cid 106537
Former Editor: Michael Blain, Google, [email protected], 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
</pre>
<pre class="anchors">
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
type: dfn; text: relevant settings object
url: #event-loop-processing-model; type: dfn; text: HTML Processing Model
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: #content-area; type: dfn; text: content area
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/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
</pre>
<pre class="link-defaults">
spec: css-values-3; type: dfn
text: absolute length
text: dimension
spec:html; type:attribute; text:document
</pre>
<h2 id='introduction'>Introduction</h2>
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,
<a href="http://www.iab.net/iablog/2014/03/viewability-has-arrived-what-you-need-to-know-to-see-through-this-sea-change.html">
ad networks now require reporting of ad "visibility" for monetizing impressions</a>. This has led to many sites abusing scroll handlers
(causing jank on scroll),
<a href="http://gent.ilcore.com/2011/03/how-not-to-trigger-layout-in-webkit.html">
synchronous layout invoking readbacks</a>
(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 <a>viewport</a>).
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 <a>viewport</a>.
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.
<div class="example">
<pre highlight="js">
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.boundingClientRect()
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();
</pre>
</div>
<h2 id='intersection-observer-api'>Intersection Observer</h2>
The <dfn>Intersection Observer</dfn> API enables developers to understand the
visibility and position of <dfn for="IntersectionObserver">target</dfn> DOM
elements relative to an <a>intersection root</a>.
<h3 id='intersection-observer-callback'>
The IntersectionObserverCallback</h3>
<pre class="idl">
callback IntersectionObserverCallback = undefined (sequence<IntersectionObserverEntry> entries, IntersectionObserver observer);
</pre>
This callback will be invoked when there are changes to <a>target</a>'s
intersection with the <a>intersection root</a>, as per the
<a>processing model</a>.
<h3 id='intersection-observer-interface'>
The IntersectionObserver interface</h3>
The {{IntersectionObserver}} interface can be used to observe changes in the
intersection of an <a>intersection root</a> and one or more <a>target</a> {{Element}}s.
The <dfn for="IntersectionObserver">intersection root</dfn>
for an {{IntersectionObserver}} is the value of its {{IntersectionObserver/root}} attribute
if the attribute is non-<code>null</code>;
otherwise, it is the <a>top-level browsing context</a>'s {{document}} node,
referred to as the <dfn for="IntersectionObserver">implicit root</dfn>.
An {{IntersectionObserver}} with a non-<code>null</code> {{IntersectionObserver/root}}
is referred to as an <dfn for="IntersectionObserver">explicit root observer</dfn>,
and it can observe any <a>target</a> {{Element}} that is a descendant of the
{{IntersectionObserver/root}} in the <a>containing block chain</a>.
An {{IntersectionObserver}} with a <code>null</code> {{IntersectionObserver/root}}
is referred to as an <dfn for="IntersectionObserver">implicit root observer</dfn>.
Valid <a>targets</a> for an <a>implicit root observer</a> include
any {{Element}} in the <a>top-level browsing context</a>,
as well as any {{Element}} in any <a>nested browsing context</a>
which is in the <a>list of the descendant browsing contexts</a> of the <a>top-level browsing context</a>.
When dealing with <a>implicit root observers</a>, the API makes a distinction between
a <a>target</a> whose <a>relevant settings object</a>'s <a>origin</a> is
<a>same origin-domain</a> with the <a>top-level origin</a>, referred to as a
<dfn for="IntersectionObserver">same-origin-domain target</dfn>;
as opposed to a <dfn for="IntersectionObserver">cross-origin-domain target</dfn>.
Any <a>target</a> of an <a>explicit root observer</a> is also a <a>same-origin-domain target</a>,
since the <a>target</a> must be in the same <a>document</a> as the
<a>intersection root</a>.
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
<a>target</a> seems to introduce more complexity without solving additional
use-cases. Per-{{observe()}} options could be provided in the future if the need arises.
<pre class="idl">
[Exposed=Window]
interface IntersectionObserver {
constructor(IntersectionObserverCallback callback, optional IntersectionObserverInit options = {});
readonly attribute (Element or Document)? root;
readonly attribute DOMString rootMargin;
readonly attribute FrozenArray<double> thresholds;
undefined observe(Element target);
undefined unobserve(Element target);
undefined disconnect();
sequence<IntersectionObserverEntry> takeRecords();
};
</pre>
<div dfn-type="method" dfn-for="IntersectionObserver">
: <dfn constructor lt="IntersectionObserver(callback, options)">
new IntersectionObserver(callback, options)</dfn>
::
Return the result of running the <a>initialize a new IntersectionObserver</a>
algorithm, providing |callback| and |options|.
: <dfn>observe(target)</dfn>
::
Run the <a>observe a target Element</a> algorithm, providing |this| and |target|.
: <dfn>unobserve(target)</dfn>
::
Run the <a>unobserve a target Element</a> algorithm, providing |this| and |target|.
Note: {{MutationObserver}} does not implement {{unobserve()}}.
For {{IntersectionObserver}}, {{unobserve()}} addresses the
lazy-loading use case. After |target| becomes visible,
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|.
: <dfn>disconnect()</dfn>
::
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.
: <dfn>takeRecords()</dfn>
::
1. Let |queue| be a copy of |this|'s internal {{[[QueuedEntries]]}} slot.
2. Clear |this|'s internal {{[[QueuedEntries]]}} slot.
3. Return |queue|.
</div>
<div dfn-type="attribute" dfn-for="IntersectionObserver">
: <dfn>root</dfn>
::
The {{IntersectionObserverInit/root}} provided to the {{IntersectionObserver}} constructor, or <code>null</code> if none was provided.
: <dfn>rootMargin</dfn>
::
Offsets applied to the <a>root intersection rectangle</a>,
effectively growing or shrinking the box that is used to calculate intersections.
<b>These offsets are only applied when handling <a>same-origin-domain targets</a>;
for <a>cross-origin-domain targets</a> they are ignored.</b>
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".
: <dfn>thresholds</dfn>
::
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, the value of this attribute will be [0].
</div>
The <dfn for=IntersectionObserver>root intersection rectangle</dfn>
for an {{IntersectionObserver}}
is the rectangle we'll use to check against the targets.
<dl class=switch>
<dt>If the {{IntersectionObserver}} is an <a>implicit root observer</a>,
<dd>it's treated as if the root were the <a>top-level browsing context</a>'s {{document}}, according to the following rule for {{document}}.
<dt>If the <a>intersection root</a> is a {{document}},
<dd>it's the size of the {{document}}'s <a>viewport</a> (note that this processing step can only be reached if the {{document}} is <a>fully active</a>).
<dt>Otherwise, if the <a>intersection root</a> has an overflow clip,
<dd>it's the element's <a>content area</a>.
<dt>Otherwise,
<dd>it's the result of running the {{Element/getBoundingClientRect()}} algorithm on the <a>intersection root</a>.
</dl>
When calculating the <a>root intersection rectangle</a> for
a <a>same-origin-domain target</a>, 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 <a>intersection root</a> itself.
If a <a>target</a> {{Element}} is clipped by an ancestor other than the
<a>intersection root</a>, that clipping is unaffected by
{{IntersectionObserver/rootMargin}}.
Note: <a>Root intersection rectangle</a> is not affected by
<a>pinch zoom</a> and will report the unadjusted <a>viewport</a>, consistent with the
intent of pinch zooming (to act like a magnifying glass and NOT change layout.)
To <dfn>parse a root margin</dfn>
from an input string |marginString|,
returning either a list of 4 pixel lengths or percentages,
or failure:
1. <a>Parse a list of component values</a> |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 <a>absolute length</a> <a>dimension</a> token,
replace it with a an equivalent pixel length.
* If |token| is a <<percentage>> 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|.
<h3 id="intersection-observer-entry">
The IntersectionObserverEntry interface</h3>
<pre class="idl">
[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 double intersectionRatio;
readonly attribute Element target;
};
dictionary IntersectionObserverEntryInit {
required DOMHighResTimeStamp time;
required DOMRectInit? rootBounds;
required DOMRectInit boundingClientRect;
required DOMRectInit intersectionRect;
required boolean isIntersecting;
required double intersectionRatio;
required Element target;
};
</pre>
<div dfn-type="attribute" dfn-for="IntersectionObserverEntry">
: <dfn>boundingClientRect</dfn>
::
A {{DOMRectReadOnly}} obtained by running the {{Element/getBoundingClientRect()}} algorithm
on the {{IntersectionObserverEntry/target}}.
: <dfn>intersectionRect</dfn>
::
{{IntersectionObserverEntry/boundingClientRect}}, intersected by
each of {{IntersectionObserverEntry/target}}'s ancestors' clip
rects (up to but not including {{IntersectionObserver/root}}),
intersected with the <a>root intersection rectangle</a>.
This value represents the portion of
{{IntersectionObserverEntry/target}} actually visible
within the <a>root intersection rectangle</a>.
: <dfn>isIntersecting</dfn>
::
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).
: <dfn>intersectionRatio</dfn>
::
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.
: <dfn>rootBounds</dfn>
::
For a <a>same-origin-domain target</a>, this will be the <a>root intersection rectangle</a>.
Otherwise, this will be <code>null</code>.
Note that if the target is in a different <a>browsing context</a> than the <a>intersection root</a>,
this will be in a different coordinate system
than {{IntersectionObserverEntry/boundingClientRect}} and {{IntersectionObserverEntry/intersectionRect}}.
: <dfn>target</dfn>
::
The {{Element}} whose intersection with the
<a>intersection root</a> changed.
: <dfn>time</dfn>
::
The attribute must return a {{DOMHighResTimeStamp}}
that corresponds to the time the intersection was recorded, relative to the
<a>time origin</a> of the global object associated with the IntersectionObserver instance
that generated the notification.
</div>
<h3 id="intersection-observer-init">
The IntersectionObserverInit dictionary</h3>
<pre class="idl">
dictionary IntersectionObserverInit {
(Element or Document)? root = null;
DOMString rootMargin = "0px";
(double or sequence<double>) threshold = 0;
};
</pre>
<div dfn-type="dict-member" dfn-for="IntersectionObserverInit">
: <dfn>root</dfn>
::
The {{IntersectionObserver|root}} to use for intersection.
If not provided, use the <a>implicit root</a>.
: <dfn>rootMargin</dfn>
::
Similar to the CSS 'margin' property,
this is a string of 1-4 components,
each either an <a>absolute length</a> or a percentage.
<pre class="example" highlight=js>
"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
</pre>
: <dfn>threshold</dfn>
::
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 running the {{Element/getBoundingClientRect()}} algorithm
on the <a>target</a>.
Note: 0.0 is effectively "any non-zero number of pixels".
</div>
<h2 dfn id='intersection-observer-processing-model'>
Processing Model</h2>
This section outlines the steps the user agent must take when implementing
the <a>Intersection Observer</a> API.
<h3 id='defines'>
Internal Slot Definitions</h3>
<h4 id='document-defines'>
Document</h4>
Each {{document}} has an
<dfn for="Document">IntersectionObserverTaskQueued</dfn> flag
which is initialized to false.
<h4 id='element-private-slots'>
Element</h4>
{{Element}} objects have an internal
<dfn attribute for=Element>\[[RegisteredIntersectionObservers]]</dfn> slot,
which is initialized to an empty list.
This list holds <dfn interface>IntersectionObserverRegistration</dfn> records,
which have an <dfn attribute for=IntersectionObserverRegistration>observer</dfn> property
holding an {{IntersectionObserver}}, a <dfn attribute for=IntersectionObserverRegistration>previousThresholdIndex</dfn> property
holding a number between -1 and the length of the observer's {{IntersectionObserver/thresholds}} property (inclusive), and
a <dfn attribute for=IntersectionObserverRegistration>previousIsIntersecting</dfn> property holding a boolean.
<h4 id='intersection-observer-private-slots'>
IntersectionObserver</h4>
{{IntersectionObserver}} objects have internal
<dfn attribute for=IntersectionObserver>\[[QueuedEntries]]</dfn> and
<dfn attribute for=IntersectionObserver>\[[ObservationTargets]]</dfn> slots,
which are initialized to empty lists and an internal
<dfn attribute for=IntersectionObserver>\[[callback]]</dfn> slot
which is initialized by {{IntersectionObserver(callback, options)}}</a>.
They also have an internal <dfn attribute for=IntersectionObserver>\[[rootMargin]]</dfn> slot
which is a list of four pixel lengths or percentages.
<h3 id='algorithms'>
Algorithms</h2>
<h4 id='initialize-new-intersection-observer'>Initialize a new IntersectionObserver</h4>
To <dfn>initialize a new IntersectionObserver</dfn>, 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 <a>parse a root margin</a>
from |options|.{{IntersectionObserverInit/rootMargin}}.
If a list is returned,
set |this|'s internal {{[[rootMargin]]}} slot to that.
Otherwise, <a>throw</a> a {{SyntaxError}} exception.
4. Let |thresholds| be a list equal to
|options|.{{IntersectionObserverInit/threshold}}.
5. If any value in |thresholds| is less than 0.0 or greater than
1.0, <a>throw</a> a {{RangeError}} exception.
6. Sort |thresholds| in ascending order.
7. If |thresholds| is empty, append <code>0</code> to |thresholds|.
8. The {{IntersectionObserver/thresholds}} attribute getter will return
this sorted |thresholds| list.
9. Return |this|.
<h4 id='observe-target-element'>Observe a target Element</h4>
To <dfn>observe a target Element</dfn>, 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 <code>-1</code>,
and a {{IntersectionObserverRegistration/previousIsIntersecting}} property set to <code>false</code>.
3. Append |intersectionObserverRegistration|
to |target|'s internal {{[[RegisteredIntersectionObservers]]}} slot.
4. Add |target| to |observer|'s internal {{[[ObservationTargets]]}} slot.
<h4 id='unobserve-target-element'>Unobserve a target Element</h4>
To <dfn>unobserve a target Element</dfn>, 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
<h4 id='queue-intersection-observer-task'>
Queue an Intersection Observer Task</h4>
The <dfn>IntersectionObserver task source</dfn> is a [=task source=] used for
scheduling tasks to [[#notify-intersection-observers-algo]].
To <dfn>queue an intersection observer task</dfn> for a {{document}} |document|,
run these steps:
1. If |document|'s <a>IntersectionObserverTaskQueued</a> flag is set to true,
return.
2. Set |document|'s <a>IntersectionObserverTaskQueued</a> flag to true.
3. <a>Queue a task</a> on the <a>IntersectionObserver task source</a>
associated with the {{document}}'s <a>event loop</a>
to <a>notify intersection observers</a>.
<h4 id='notify-intersection-observers-algo'>
Notify Intersection Observers</h4>
To <dfn>notify intersection observers</dfn> for a {{document}} |document|,
run these steps:
1. Set |document|'s <a>IntersectionObserverTaskQueued</a> 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 <a>callback this value</a>.
If this throws an exception, <a>report the exception</a>.
<h4 id='queue-intersection-observer-entry-algo'>
Queue an IntersectionObserverEntry</h4>
To <dfn>queue an IntersectionObserverEntry</dfn> 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. <a>Queue an intersection observer task</a> for |document|.
<h4 id='calculate-intersection-rect-algo'>
Compute the Intersection of a Target Element and the Root</h4>
To <dfn>compute the intersection</dfn> between a <a>target</a> and the observer's <a>intersection root</a>,
run these steps:
1. Let |intersectionRect| be the result of running the {{Element/getBoundingClientRect()}} algorithm on the <a>target</a>.
2. Let |container| be the <a>containing block</a> of the <a>target</a>.
3. While |container| is not the <a>intersection root</a>:
1. If |container| is the {{document}} of a <a>nested browsing context</a>,
update |intersectionRect| by clipping to the <a>viewport</a>
of the {{document}}, and update |container| to be
the <a>browsing context container</a> of |container|.
2. Map |intersectionRect| to the coordinate space of |container|.
3. If |container| has overflow clipping or a css <a>clip-path</a> property,
update |intersectionRect| by applying |container|'s clip.
4. If |container| is the root element of a <a>browsing context</a>,
update |container| to be the <a>browsing context</a>'s {{document}};
otherwise, update |container| to be the <a>containing block</a>
of |container|.
4. Map |intersectionRect| to the coordinate space of the <a>intersection root</a>.
5. Update |intersectionRect| by intersecting it with the <a>root intersection rectangle</a>.
6. Map |intersectionRect| to the coordinate space of the <a>viewport</a> of the {{document}} containing the <a>target</a>.
7. Return |intersectionRect|.
<h4 id='update-intersection-observations-algo'>
Run the Update Intersection Observations Steps</h4>
To <dfn>run the update intersection observations steps</dfn> 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 <a>top-level browsing context</a>, this includes <a>implicit root observers</a>.
2. For each |observer| in |observer list|:
1. Let |rootBounds| be |observer|'s <a>root intersection rectangle</a>.
2. For each |target| in |observer|'s internal {{[[ObservationTargets]]}} slot, processed in the same order that {{observe()}} was called on each |target|:
1. 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.
2. If the <a>intersection root</a> is not the <a>implicit root</a>,
and |target| is not in the same {{document}} as the <a>intersection root</a>,
skip to step 11.
3. If the <a>intersection root</a> is an {{Element}},
and |target| is not a descendant of the <a>intersection root</a>
in the <a>containing block chain</a>, skip to step 11.
4. Set |targetRect| to the {{DOMRectReadOnly}} obtained
by running the {{Element/getBoundingClientRect()}} algorithm on |target|.
5. Set |intersectionRect| to the result of running the <a>compute the intersection</a>
algorithm on |target|.
6. Let |targetArea| be |targetRect|'s area.
7. Let |intersectionArea| be |intersectionRect|'s area.
8. Set |isIntersecting| to true if |targetRect| and |rootBounds| intersect or are edge-adjacent,
even if the intersection has zero area (because |rootBounds| or |targetRect| have
zero area).
9. If |targetArea| is non-zero, let |intersectionRatio| be |intersectionArea| divided by |targetArea|.<br>
Otherwise, let |intersectionRatio| be <code>1</code> if |isIntersecting| is true, or <code>0</code> if |isIntersecting| is false.
10. 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}}.
11. Let |intersectionObserverRegistration| be the {{IntersectionObserverRegistration}} record
in |target|'s internal {{[[RegisteredIntersectionObservers]]}} slot
whose {{IntersectionObserverRegistration/observer}} property is equal to |observer|.
12. Let |previousThresholdIndex| be the |intersectionObserverRegistration|'s
{{IntersectionObserverRegistration/previousThresholdIndex}} property.
13. Let |previousIsIntersecting| be the |intersectionObserverRegistration|'s
{{IntersectionObserverRegistration/previousIsIntersecting}} property.
14. If |thresholdIndex| does not equal |previousThresholdIndex| or if
|isIntersecting| does not equal |previousIsIntersecting|,
<a>queue an IntersectionObserverEntry</a>,
passing in |observer|, |time|, |rootBounds|,
|targetRect|, |intersectionRect|, |isIntersecting|, and |target|.
15. Assign |thresholdIndex| to |intersectionObserverRegistration|'s
{{IntersectionObserverRegistration/previousThresholdIndex}} property.
16. Assign |isIntersecting| to |intersectionObserverRegistration|'s
{{IntersectionObserverRegistration/previousIsIntersecting}} property.
<h3 id='lifetime'>
IntersectionObserver Lifetime</h2>
An {{IntersectionObserver}} will remain alive until both of these conditions hold:
<ul>
<li>There are no scripting references to the observer.</li>
<li>The observer is not observing any targets.
</ul>
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.
<h3 id='external-spec-integrations'>
External Spec Integrations</h3>
<h4 id='event-loop'>
HTML Processing Model: Event Loop</h4>
An <a>Intersection Observer</a> processing step should take place
during the "<i>Update the rendering</i>" steps,
after step 12, <a>run the animation frame callbacks</a>,
in the in the <a>HTML Processing Model</a>.
This step is:
<ol start="13">
<li>For each <a>fully active</a> {{document}} in |docs|, <a>Run the update intersection observations steps</a> for that {{document}}, passing in |now| as the timestamp.</li>
</ol>
<h4 id='pending-initial-observation'>Pending initial IntersectionObserver targets</h4>
A {{document}} is said to have <dfn>pending initial IntersectionObserver targets</dfn>
if there is at least one {{IntersectionObserver}} meeting these criteria:
<ol>
<li>The |observer|'s {{IntersectionObserver|root}} is in the |document|
(for the <a>top-level browsing context</a>, this includes <a>implicit root observers</a>).
</li>
<li>The |observer| has at least one |target| in its {{[[ObservationTargets]]}} slot for which
no {{IntersectionObserverEntry}} has yet been queued.
</li>
</ol>
In the <a>HTML Processing Model</a>, under the "<i>Update the rendering</i>" step, the "<i>Unnecessary rendering</i>" step should be modified to add an additional requirement for skipping the rendering update:
<ul><li>The |document| does not have <a>pending initial IntersectionObserver targets</a>.</li></ul>
<!-- ============================================================ -->
<h2 id=accessibility>Accessibility Considerations</h2>
<!-- ============================================================ -->
*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
<a href="https://githumb.com/WICG/spatial-navigation">spatial navigation</a>.
<!-- ============================================================ -->
<h2 id=privacy>Privacy and Security</h2>
<!-- ============================================================ -->
*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 <a>cross-origin-domain target</a> 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 suppressing {{IntersectionObserverEntry/rootBounds}}
for <a>cross-origin-domain targets</a> 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.
<!-- ============================================================ -->
<h2 id=internationalization>Internationalization</h2>
<!-- ============================================================ -->
*This section is non-normative.*
There are no known issues concerning internationalization.
<!-- ============================================================ -->
<h2 id=acknowledgements>Acknowledgements</h2>
<!-- ============================================================ -->
Special thanks to <a href="https://github.com/w3c/IntersectionObserver/graphs/contributors">all the contributors</a> for their technical input and suggestions that led to improvements to this
specification.