Skip to content

Instantly share code, notes, and snippets.

@insin
Created May 11, 2023 09:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save insin/a743249ed7a0f8b60f51537e1c4354aa to your computer and use it in GitHub Desktop.
Save insin/a743249ed7a0f8b60f51537e1c4354aa to your computer and use it in GitHub Desktop.
Lightweight YouTube embed component for Astro
---
export interface Props {
title: string
videoCode: string
}
let {title, videoCode} = Astro.props
let playButtonSvg = `<svg height="100%" version="1.1" viewBox="0 0 68 48" width="100%"><path d="M66.52,7.74c-0.78-2.93-2.49-5.41-5.42-6.19C55.79,.13,34,0,34,0S12.21,.13,6.9,1.55 C3.97,2.33,2.27,4.81,1.48,7.74C0.06,13.05,0,24,0,24s0.06,10.95,1.48,16.26c0.78,2.93,2.49,5.41,5.42,6.19 C12.21,47.87,34,48,34,48s21.79-0.13,27.1-1.55c2.93-0.78,4.64-3.26,5.42-6.19C67.94,34.95,68,24,68,24S67.94,13.05,66.52,7.74z" fill="#f00"></path><path d="M 45,24 27,14 27,34" fill="#fff"></path></svg>`
let srcdoc = `<style>*{padding:0;margin:0;overflow:hidden}html,body{height:100%}img{position:absolute;width:100%;top:0;bottom:0;margin:auto}.button{position:absolute;left:50%;top:50%;width:68px;height:48px;margin-left:-34px;margin-top:-24px;}.top{position:absolute;top:18px;left:18px;right:18px;display:flex;flex-wrap:nowrap}.title{color:#fff;font-size:18px;white-space:nowrap;word-wrap:normal;text-shadow:0 0 2px rgba(0,0,0,.5);font-family:"YouTube Noto",Roboto,Arial,Helvetica,sans-serif;line-height:1.3;text-overflow:ellipsis;overflow:hidden;}</style><a href="https://www.youtube.com/embed/${videoCode}?autoplay=1"><img src="https://img.youtube.com/vi/${videoCode}/sddefault.jpg" alt="${title}"><div class="top"><div class="title">${title}</div></div><div class="button">${playButtonSvg}</div></a>`
---
<iframe
class="w-full aspect-video rounded"
src={`https://www.youtube.com/embed/${videoCode}`}
title={title}
srcdoc={srcdoc}
frameborder="0"
allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen>
</iframe>
@insin
Copy link
Author

insin commented Sep 27, 2023

An improved version of this is now available on npm: https://github.com/insin/astro-lazy-youtube-embed#readme

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment