Understanding the IntersectionObserver API | by Emil Hein | May, 2022

It’s not practically as scary because it sounds and I’ll present you

How does the Intersection observer staff

The IntersectionObserver is a browser API supported in all main browsers. It has a considerably scary title and a bit complicated API. However that shouldn’t forestall us from utilizing it, because it gives us with some fairly cool options.

Normally, this API is ideal for:

  • Lazyloading issues
  • Monitoring in-view metrics for components
  • Infinite scroll

In brief, the API can assist decide if an HTML factor is intersecting one other or extra generally if a component is intersecting the viewport.

With a high-level view, the API wants 3 issues

  1. A HTML factor
  2. A configuration object
  3. A callback perform

For the reason that API is a bit unusual, I’ve written a bit wrapper to assist use the API

Wrapper for IntersectionObserver API

Now I’m not going to enter specifics concerning the parameters, as they’re deeply described here

I’m gonna use a easy instance with an HTML factor with id goal and configurations that can execute the callback perform every time that factor “intersects” the viewport.

The way in which to eat the above wrapper appears to be like like this

With these two items, we are able to shortly put collectively a demo that may use this performance

StackBlitz instance

All of the above instance does is print one thing to the console and alter some textual content. However in case you begin constructing extra logic round this sample, you can begin lazy loading a few of your code or pictures (though <img loading=lazy> is likely to be supported extensively quickly)

You should use the above for inner monitoring, to rely how many individuals scroll to a sure level in your web page.

In my skilled job, we use the above, to detect every time a component comes into the viewport and refresh it (an exterior useful resource) if it has been greater than 30 seconds because it was final refreshed.

I at all times love utilizing Browser APIs every time I can, because it saves me a whole lot of complications making an attempt to account for edge circumstances.

Keep lazy!

More Posts