justinribeiro / lite-youtube

The fastest little YouTube web component on this side of the internet. The shadow dom web component version of Paul's lite-youtube-embed.
https://www.npmjs.com/package/@justinribeiro/lite-youtube
MIT License
836 stars 63 forks source link

Best method to avoid Cumulative Layout Shift? #85

Closed NathanBeddoeWebDev closed 1 year ago

NathanBeddoeWebDev commented 1 year ago

Hey, love the facade, definitely helps to decrease the Time to Interactive and Total Blocking Time on the page.

We are experiencing a large amount of Cumulative Layout Shift since implementing lite-youtube, and was wondering if any of the contributors or users of the component have solved this. The native iframe didn't seem to have this issue.

Is there a way that I can get the height and width of the video earlier, or apply styles to the component to avoid this?

justinribeiro commented 1 year ago

Is there a way that I can get the height and width of the video earlier

That's going to depend on the container you've placed lite-youtube in. lite-youtube has :host styles that set it's width to 100% and then calculate the 16:9 ratio.

apply styles to the component to avoid this

If you know the context of where lite-youtube is on the page, you can style before the custom element lifecycle upgrades to prevent the shift. You could use similar code as the aforemetioned :host style:

https://github.com/justinribeiro/lite-youtube/blob/c301ef2e6c22f01ba97e8b2cc472681c224c0016/lite-youtube.ts#L120-L126

to do something along the lines of:

lite-youtube {
    display: block;
    position: relative;
    width: 100%;
    padding-bottom: calc(100% / (16 / 9));
}

On upgrade, the container then won't create a CLS (ala, it won't push content down on the lazy load).

NathanBeddoeWebDev commented 1 year ago

Works like a charm image Legend, thanks mate.