ろぼいんブログ
更新:

AstroにYouTubeを埋め込む「astro-embed-youtube」の使い方

astro-embed-youtubeの公式ドキュメントのスクリーンショット

Astro は、近年人気が高まっている静的サイトジェネレーターです。フレームワークに依存せず、フロントエンドで動作させる必要があるスクリプトがないため、高速なページ読み込みが特徴です。

しかし、AstroでYouTubeの通常の埋め込みコードを使用すると、ページの読み込み速度が低下し、 PageSpeed Insights などのツールで評価が下がってしまいます。これは、YouTubeの埋め込みコードが速度を重視していないため、

(window.powerTag.Init = window.powerTag.Init || []).push(function () { window.powerAPITag.display("pw_41759"); });

そこで、この記事ではパフォーマンスを維持しながらAstroベースのサイトにYouTubeを埋め込める「 astro-embed-youtube 」を紹介します。

astro-embed-youtubeとは?

astro-embed-youtubeの公式ドキュメントのスクリーンショット
画像: astro-embed-youtubeの公式ドキュメント

astro-embed-youtubeは、AstroにYouTubeを埋め込むためのコンポーネントです。

通常のYouTubeの埋め込みコードは、ページの読み込み速度を低下させてしまいます。一方で、astro-embed-youtubeを使用することでパフォーマンスを維持しながらYouTubeを埋め込めます。

astro-embed-youtubeの内部では Lite YouTube Embed が使われています。動画が埋め込まれた箇所には、デフォルトではサムネイル画像とYouTubeのロゴのみが表示されます。ユーザーがクリックしてはじめてYouTubeの``iframe``が読み込まれるため、ページの読み込み速度が低下しません。

Lite YouTube Embedの公式ドキュメントによると、YouTubeの埋め込みを224倍高速にレンダリングできるとのことです。

astro-embed-youtubeを使うと、このLite YouTube EmbedをAstroで簡単に利用できます。

インストール方法

astro-embed-youtubeは、次のコマンドでインストールできます。

try{(()=>{function a(e){if(!e)return;let t=e.getAttribute("tabindex")!==null,n=e.scrollWidth>e.clientWidth;n&&!t?e.setAttribute("tabindex","0"):!n&&t&&e.removeAttribute("tabindex")}var u=window.requestIdleCallback||(e=>setTimeout(e,1)),i=window.cancelIdleCallback||clearTimeout;function l(e){let t=new Set,n,r;return new ResizeObserver(c=>{c.forEach(o=>t.add(o.target)),n&&clearTimeout(n),r&&i(r),n=setTimeout(()=>{r&&i(r),r=u(()=>{t.forEach(o=>e(o)),t.clear()})},250)})}function d(e,t){e.querySelectorAll?.(".expressive-code pre > code").forEach(n=>{let r=n.parentElement;r&&t.observe(r)})}var s=l(a);d(document,s);var b=new MutationObserver(e=>e.forEach(t=>t.addedNodes.forEach(n=>{d(n,s)})));b.observe(document.body,{childList:!0,subtree:!0});document.addEventListener("astro:page-load",()=>{d(document,s)});})();}catch(e){console.error("[EC] tabindex-js-module failed:",e)}try{(()=>{function i(o){let e=document.createElement("pre");Object.assign(e.style,{opacity:"0",pointerEvents:"none",position:"absolute",overflow:"hidden",left:"0",top:"0",width:"20px",height:"20px",webkitUserSelect:"auto",userSelect:"all"}),e.ariaHidden="true",e.textContent=o,document.body.appendChild(e);let a=document.createRange();a.selectNode(e);let n=getSelection();if(!n)return!1;n.removeAllRanges(),n.addRange(a);let r=!1;try{r=document.execCommand("copy")}finally{n.removeAllRanges(),document.body.removeChild(e)}return r}async function l(o){let e=o.currentTarget,a=e.dataset,n=!1,r=a.code.replace(/\u007f/g,` `);try{await navigator.clipboard.writeText(r),n=!0}catch{n=i(r)}if(!n||e.parentNode?.querySelector(".feedback"))return;let t=document.createElement("div");t.classList.add("feedback"),t.append(a.copied),e.before(t),t.offsetWidth,requestAnimationFrame(()=>t?.classList.add("show"));let c=()=>!t||t.classList.remove("show"),d=()=>{!t||parseFloat(getComputedStyle(t).opacity)>0||(t.remove(),t=void 0)};setTimeout(c,1500),setTimeout(d,2500),e.addEventListener("blur",c),t.addEventListener("transitioncancel",d),t.addEventListener("transitionend",d)}function s(o){o.querySelectorAll?.(".expressive-code .copy button").forEach(e=>e.addEventListener("click",l))}s(document);var u=new MutationObserver(o=>o.forEach(e=>e.addedNodes.forEach(a=>{s(a)})));u.observe(document.body,{childList:!0,subtree:!0});document.addEventListener("astro:page-load",()=>{s(document)});})();}catch(e){console.error("[EC] copy-js-module failed:",e)}
Terminal window
npm install @astro-community/astro-embed-youtube

使い方

インストールが完了したら、MDXファイルやAstroファイルからコンポーネントを読み込みます。MDXファイルの場合は任意の場所、Astroファイルの場合は---ブロック内でインポートします。

(window.powerTag.Init = window.powerTag.Init || []).push(function () { window.powerAPITag.display("pw_41759"); });

```mdx title="index.mdx"
通常のコンテンツを入力
```

```astro title="index.astro"

---

---


(window.powerTag.Init = window.powerTag.Init || []).push(function () { window.powerAPITag.display("pw_41759"); });

通常のコンテンツを入力
```


次に、YouTubeの動画を埋め込みたい箇所でYouTubeコンポーネントを使います。id属性には動画のIDを指定します。すると、動画が埋め込まれます。

<YouTube id="5u0Ds7wzUeI" />

オプション

astro-embed-youtubeのYouTubeコンポーネントには、いくつかのオプションが用意されています。ここでは、主要なオプションを紹介します。他にもいくつかのオプションが用意されているので、詳細は 公式ドキュメント を参照してください。

サムネイルを変更する

サムネイルを変更するには、poster属性にサムネイル画像のURLを指定します。

<YouTube id="5u0Ds7wzUeI" poster="https://example.com/thumbnail.jpg" />

こうすることで、指定したURLの画像がサムネイルとして使用されます。サムネイル画像はユーザーがコンポーネントをクリックするまで表示されます。

サムネイルの解像度を変更する

サムネイルの解像度を変更するには、posterQuality属性に解像度を示す文字列を指定します。posterQuality属性には次の値を使用できます。

<YouTube id="5u0Ds7wzUeI" posterQuality="high" />

パラメーターを指定する

YouTubeでは、再生時間を指定したり、埋め込みの動作を変更するためのパラメーターが用意されています。astro-embed-youtubeでは、params属性を使ってパラメーターを指定できます。たとえば、動画の10秒から再生する場合は、次のように指定します。複数のパラメーターを指定する場合は、&で区切ります。

<YouTube id="5u0Ds7wzUeI" title="Starlight by Astro" />

タイトルを表示する

<iframe>が読み込まれるまでの間、サムネイル画像とYouTubeのロゴが表示されます。このとき、サムネイル画像の上に動画のタイトルを表示するには、title属性にタイトルを指定します。

<YouTube id="5u0Ds7wzUeI" title="Starlight by Astro" />

まとめ

この記事では、AstroにYouTubeを埋め込むためのコンポーネント「astro-embed-youtube」を紹介しました。

通常のYouTubeの埋め込みコードは、ページの読み込み速度を低下させてしまいます。一方で、astro-embed-youtubeを使用することでパフォーマンスを維持しながらYouTubeを埋め込めます。

astro-embed-youtubeを使うことで、AstroベースのサイトにYouTubeを埋め込めます。ぜひ、astro-embed-youtubeを使ってみてください。

参考

おすすめアイテム

※このリンクを経由して商品を購入すると、当サイトの運営者が報酬を得ることがあります。詳細はこちら

このサイトを支援する

Buy Me a CoffeeまたはGitHub Sponsorsで支援していただけると、サイトの運営やコンテンツ制作の励みになります。定期的な支援と一度限りの支援がありますので、お間違いのないようにお願いします。

Buy me a coffee

著者のアイコン画像

生まれた時から、母国語よりも先にJavaScriptを使っていました。ネットの海のどこにもいなくてどこにでもいます。

Webフロントエンドプログラマーで、テクノロジーに関する話題を追いかけています。動画編集やプログラミングが趣味で、たまにデザインなどもやっています。主にTypeScriptを使用したWebフロントエンド開発を専門とし、便利で実用的なブラウザー拡張機能を作成しています。また、個人ブログを通じて、IT関連のニュースやハウツー、技術的なプログラミング情報を発信しています。