DEV Community

Cover image for Embedding Youtube Videos in a Performant Way
Paweł Kowalski for platformOS

Posted on • Originally published at documentation.platformos.com

Embedding Youtube Videos in a Performant Way

Sometimes you want to share a Youtube video on your website, instead of just pasting a link. The problem with this is that Youtube will load over 1.5 MB of scripts (including tracking code), styles, and HTML even if the user is not interested in the video at all.

Default

This is the default embed code that is proposed by Youtube:

<iframe
  width="560"
  height="315"
  src="https://www.youtube.com/embed/evezbNPC0Mo"
  frameborder="0"
  allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
  allowfullscreen>
</iframe>
Enter fullscreen mode Exit fullscreen mode

Low-tech solution

There is a pretty nice workaround to provide a visually pleasing video for your user without making the site slow and heavy. You can use the thumbnail from Youtube and link it to the video, so the user would click an image and go to Youtube to watch the video.

<a href="https://www.youtube.com/watch?v=evezbNPC0Mo" target="_blank">
  <img src="images/thumbnail.jpg" alt="Town Hall #77 - How platformOS cloning revolutionized web development">
</a>
Enter fullscreen mode Exit fullscreen mode

Example:


Town Hall #77 - How platformOS cloning revolutionized web development

High-tech solution

Now there is a better way: Lite YouTube Embed

Lite YouTube Embed is a script that registers a custom element in the browser. This element shows a Youtube player that's very similar to original, but:

  1. It is not downloading anything but the thumbnail until the user clicks play
  2. It uses the youtube-nocookie.com domain instead of youtube.com, which strips out tracking cookies, preserving your users' privacy
  3. According to the readme, because of deferred loading of resources, it renders 224x faster than the original player
  4. It replaces static thumbnail with original Youtube player after user decided he is interested in watching the video

To be able to use this custom element in its full potential, you need its CSS and javascript loaded on your website.

The custom element is straightforward to use:

<lite-youtube videoid="evezbNPC0Mo">
</lite-youtube>
Enter fullscreen mode Exit fullscreen mode

See live demos.

Top comments (0)