HomeBikeshedComponents

lite-yt.html

Published:

I’ve wanted to embed YouTube videos to my site for a while now, but I was always too scared to do it. Also, it came with a lot of performance issues that I thought were so bad I removed it. Well, there’s a lot of YouTube videos I’d like to include on this site and I’ve also found a way to do it performantly.

With the help of Paul Irish’s Lite YouTube Embed implementation, I’ve made the lite-yt.html shortcode to improve web performance by loading the video only when requested. This makes a page load 0.4s with 117KB vs 3.5s with 3.9MB—6× faster using 3% of the data1. It’s also progressivley enhanced so it’ll work in RSS just fine. It still needs a bit of tidying up but it should be good for now. Once you’re done with this, see my first post using this shortcode.

Usage and Example

First you’ll need to include the partial lite-yt.html in your header so that the embed’s scripts only load when the lite-yt shortcode is detected.

{{ partial "lite-yt.html" . }}

Then you make a partial like this:

{{< lite-yt id="" title="" params="" ytapi="" >}}
  • id is the id of the video—the v parameter. So for the video https://www.youtube.com/watch?v=dQw4w9WgXcQ, the id will be dQw4w9WgXcQ
  • title is the name of the video.
  • params is the param string containing any embed settings you would like to have.
  • ytapi should be specified if you want to use the YouTube Player API.

Here’s an example using this cool video:

Play Video: Rick Astley - Never Gonna Give You Up (Official Music Video)

Source Code

partials/lite-yt.html

{{ if .HasShortcode "lite-yt" -}}
{{/* YouTube Lite Embed, see https://www.farai.xyz/bikeshed/components/lite-yt/ */}}
{{- $ytCss := resources.Get "lite-yt-embed/lite-yt-embed.css" | resources.Fingerprint -}}
{{- $ytJs := resources.Get "lite-yt-embed/lite-yt-embed.js" | resources.Fingerprint -}}
<link rel="stylesheet" href="{{ $ytCss.RelPermalink }}">
<script src="{{ $ytJs.RelPermalink }}" async></script>
{{- end }}

shortcodes/lite-yt.html

{{- $id := or (.Get 0) (.Get "id") -}}
<lite-youtube videoId="{{ $id }}" style="background-image: url('https://i.ytimg.com/vi/{{ $id }}/hqdefault.jpg');" {{ with (.Get `title`) -}}title="{{ . }}" {{- end }} {{- with .Get `params` -}}params="{{ trim . `?&` }}"{{- end }} {{ if (.Get `ytapi`) }}yt-api{{- end }}>
    <a href="https://www.youtube.com/watch?v={{ $id }}{{- with .Get `params` -}}?{{ trim . `?&` }}{{- end -}}" class="lty-playbtn" title="Play Video{{ with (.Get `title`) -}}: {{ . }}{{- end }}">
        <span class="lyt-visually-hidden">
            Play Video{{ with (.Get "title") -}}: {{ . }}{{- end }}
        </span>
    </a>
</lite-youtube>

  1. Yeah so that includes the live reload script on the test server which is like 80KB, so it performs even better. Just see Paul’s comparison instead ↩︎