Faster, No-Reflow Embeds

Faster, No-Reflow Embeds

In all our excitement over Prefill Embeds (we even podcasted it), I forgot to mention a few other things that very much improve the performance of our embedded Pens overall.

1) Faster.

This one is a little silly, but it’s going to have to have an immediate impact on literally all Embedded Pens that use our recommended ei.js embed script. (By the way, we recommend that because it’s nice for progressive enhancement. It allows for useful fallback content when that script doesn’t run, like in an RSS feed.)

In order to safely query the DOM and look for the elements to enhance into an embed, we wait for the DOM to be ready. We were essentially doing this:

document.onreadystatechange = function () {
  if (document.readyState === 'complete') {
    // enhance embeds
  }
}

But, it was unnecessary for us to be waiting for complete there, which waited for things like all scripts and images to download. Instead, now we only wait for the interactive state of the document:

document.onreadystatechange = function () {
  if (document.readyState === 'interactive') {
    // enhance embeds
  }
}

Which means that embeds pop onto your page all the faster.

2) No reflow.

We’ve made another improvement that increases performance.

Because of the nature of how pages load, and since we’re using JavaScript to manipulate things, there is a little bit of time between the HTML element rendering and JavaScript kicking in and replacing that element with the embed.

Essentially an element like this:

See the Pen Team Illustration by Klare (@klare) on CodePen.

Turns into an element like this:

The trouble is that those two elements can, and probably do, have different heights. So when that height shifts, it triggered some layout shifting jank on your page. Not anymore, because now we make them the same height.

We’ve updated embeds to have a little inline styling on the original HTML element that exactly matches the height of the embed that will come in.

So this is how the HTML element comes in immediately:

Then, it enhances into an embed like this:

So because those are the exact same height, you shouldn’t experience any re-layout flow jankiness as they come in.

Note that these inline styles are only present in new embed code you copy out of CodePen. Of course, you’re free to apply a fixed height to your existing embeds as well to get this same benefit. I’ve done that myself on CSS-Tricks for all our existing embeds!

The post Faster, No-Reflow Embeds appeared first on CodePen Blog.

Related Post