reCAPTCHA の読み込み

このドキュメントでは、reCAPTCHA スクリプトタグを読み込むためのベスト プラクティスについて説明します。 この情報は、reCAPTCHA v2 と v3 の両方に適用されます。

reCAPTCHA を非同期で読み込む

reCAPTCHA のすべてのバージョンは、非同期で読み込むことができます。reCAPTCHA を読み込んでいます 不審なトラフィックを特定する能力に影響しません。期限 非同期スクリプトのパフォーマンス上のメリットを活かし、reCAPTCHA の読み込み、 おすすめします。

<script async src="https://www.google.com/recaptcha/api.js">

reCAPTCHA を非同期で読み込む場合は、reCAPTCHA を 読み込みが完了するまで使用しないでください。たとえば、次のコードは break:

<script async src="https://www.google.com/recaptcha/api.js"></script>
<script>
  // If reCAPTCHA is still loading, grecaptcha will be undefined.
  grecaptcha.ready(function(){
    grecaptcha.render("container", {
      sitekey: "ABC-123"
    });
  });
</script>

状況によっては、スクリプトの順序を調整するだけで競合を回避できる場合があります。 あります。別の方法として、 reCAPTCHA を読み込むページには、次のコード スニペットを追加します。以下を使用している場合: grecaptcha.ready() で API 呼び出しをラップするには、次のコード スニペットを追加して、 reCAPTCHA をいつでも呼び出せるようにしています。

<script async src="https://www.google.com/recaptcha/api.js"></script>
<script>
  // How this code snippet works:
  // This logic overwrites the default behavior of `grecaptcha.ready()` to
  // ensure that it can be safely called at any time. When `grecaptcha.ready()`
  // is called before reCAPTCHA is loaded, the callback function that is passed
  // by `grecaptcha.ready()` is enqueued for execution after reCAPTCHA is
  // loaded.
  if(typeof grecaptcha === 'undefined') {
    grecaptcha = {
      ready: function(cb) {
        // window.__grecaptcha_cfg is a global variable that stores reCAPTCHA's
        // configuration. By default, any functions listed in its 'fns' property
        // are automatically executed when reCAPTCHA loads.
        const c = '___grecaptcha_cfg';
        window[c] = window[c] || {};
        (window[c]['fns'] = window[c]['fns'] || []).push(cb);
      }
    };
  }

  // Usage
  grecaptcha.ready(function(){
    grecaptcha.render("container", {
      sitekey: "ABC-123"
    });
  });
</script>

代わりに、v2 API を使用しているサイトでは、 onload コールバック。reCAPTCHA が終了すると onload コールバックが実行される 読み込み中。onload コールバックは、reCAPTCHA を読み込む前に定義する必要があります。 使用します。

<script>
  const onloadCallback = function() {
    console.log("reCAPTCHA has loaded!");
    grecaptcha.reset();
  };
</script>
<script async src="https://www.google.com/recaptcha/api.js?onload=onloadCallback”></script>

reCAPTCHA を非同期で読み込むことができない場合(preconnect を含む) reCAPTCHA のリソースヒントを使用することを強くおすすめします。これにより、 スクリプトのダウンロードがパーサーをブロックする時間です。

リソースヒントの使用

ドキュメントの <head> に次のリソースヒントを含めると、 リソースを提供するのに要する時間を reCAPTCHA。preconnect リソースヒントは、ブラウザに対して 早期接続を保証します

<link rel="preconnect" href="https://www.google.com">
<link rel="preconnect" href="https://www.gstatic.com" crossorigin>

遅延読み込み

一般的に、reCAPTCHA にページに関するコンテキストが多ければ多いほど、 正当なユーザー アクションかどうかを判断するための通知を受け取れます。これは、 ユーザーに依存しない reCAPTCHA のバージョンを使用する場合に特に当てはまります。 学びました。したがって、特定の制限付きアクションが行われるまで reCAPTCHA の読み込みを待機する 行う(フォームの送信など)は、一般的には推奨されません。