By Paul Scanlon

MDX Embed Intersection Observer

If you’re not familiar with my plugin gatsby-mdx-embed have a read of this post

… or to summarize..

Gatsby MDX Embed is a Gatsby MDX plugin to embed Twitter, YouTube Instagram and many more in to your .mdx without imports!

I’ve had some great feedback about the plugin but there was always one little problem that i’ve been putting off solving… until now.

The Problem

Well, there’s two problems actually.

The First

Versions 0.0.0 to 0.0.17 worked by wrapping the root element of your Gatsby site with provider “embed” scripts. This meant that whenever a Tweet or Instagram etc provider component was found on the page the scrips would be available and the components could invoke the script which in turn renders the component in the page.

The Second

Some provider components don’t require page level scripts, instead they just invoke themselves when the pages loads and download whatever they need in order to render.

In both cases third party scripts need to be downloaded and the problem is that sometimes the component responsible for this isn’t even visible.

This is a quite unnecessary use of bandwidth!

Ideally we only want components to load scripts as we scroll them in to view… keeping Gatsby blazing fast ⚡

The Solution

In a recent post i discussed the Intersection Observer which is a really tidy way to know if a DOM element has entered the viewport or not.

This kind of functionality is perfect for MDX Embed and i’m pleased to announce that as of version 0.0.19 all provider components will lay dormant until they are within the viewport.

As and when they do intersect with the boundaries of the browser window the Intersection Observer kicks in and renders the underlying provider component, which as mentioned above then loads and invokes the provider script.

This improvement will keep you page load speeds fast and your Lighthouse scores high!

Happy embedding!


Leave a reaction and let me know how I'm doing.

  • 0
  • 0
  • 0
  • 0
  • 0
Powered byNeon