Intersection Observer API
The Intersection Observer Literal
Creating a new Intersection Observer using constructor:
1 | const observer = new IntersectionObserver(callback, options); |
callback: The function to be called whenever the target enter/leave the intersection area.options: An object that controls the condition of triggering the callback function.
options Object
The option object looks like this:
1 | const option = { |
root: the container for observation, by default is the viewport(null), but can also be other HTML elements.rootMargin: a bit like css margin, controls the size of the root container(not actual size, but the size to detect intersection). The values can only bepx.rootMargin: top, left, bottom, rightthereshold: the percentage of the observed items that triggers the callback function when entering the container.thereshold: 0.1meaning trigger the callback function when 10% of the object first enter/leave the container.
callback function
The callback function by default has two parameters:
1 | const callback = function(entries, observer){ |
entries: Since the observer can observe multiple elements at once, the state of each element will be put in theentries.- Each
entryinside theentriesis an object containing information about the observed element:
- Each
entryhas many properties:
entry.target: the element being observedentry.isIntersecting: whether the target is visible inside the root.entry.intersectionRatio: visible ratio, behaves just like thetheresholdentry.boundingClientRect: the position of the element relative to the viewportentry.time: time stamp when the callback function is triggered- …
observer: the IntersectionObserver itself- This is very useful cause we may want to stop the observation to avoid memory leakage:
observer.unobserve(entry.target): stop observing the elementobserver.disconnect: stop observing every element in the observerobserver.observe(newElement): start observing the new element
- This is very useful cause we may want to stop the observation to avoid memory leakage:
Lazy load img with IntersectionObserver
1 | <img src="blank-or-placeholder" data-src="real-url" alt=""/> |
The img will not be loaded at first but will be blank or replaced. Using js, we could let the img to load only when the user start to see it.
1 | const lazyImg = document.querySelectorAll("img[data-src]") |
The key point is to only load the img when the observer observed that the img is in the users’ view.

