AstroでGoogleアドセンスの広告を表示する

公開日:2023/8/9更新日:2023/8/9

AstroでGoogleアドセンスの広告を表示するには、元の広告コードのインラインで実行している<script>タグにis:inlineを付けます。その他のコードはそのまま読み込んでOKです。

is:inlineを付けた後のコードは以下になります。

<script is:inline>
  (adsbygoogle = window.adsbygoogle || []).push({});
</script>

サンプルコード

全体像は以下の通りです。

<html lang="ja">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width" />
    <meta name="generator" content={Astro.generator} />
  </head>
  <body>
    <main>
      <h1>Hello Astro</h1>
      <div>
        <p style="margin: 3rem;">Ad</p>
        <script
          async
          src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-****"
          crossorigin="anonymous"></script>
        <ins
          class="adsbygoogle"
          style="display:block"
          data-ad-format="autorelaxed"
          data-ad-client="ca-pub-****"
          data-ad-slot="1234567890"></ins>
        <script is:inline>
          (adsbygoogle = window.adsbygoogle || []).push({});
        </script>
      </div>
    </main>
  </body>
</html>

AstroとGoogleアドセンスは相性が良い

Next.jsNuxt.jsなど他のフレームと違い、Astroはご覧の通り非常に簡単にGoogleアドセンスを導入できます。

さらに、ビルド時に完全な静的ページを生成していること、MPAを採用していることもあり、総じてGoogleアドセンスとの相性が良いです。

APIなどのサーバーサイドの機能を使う予定がなければ、Astroでのサイト構築をおすすめします。