正在加载 reCAPTCHA

本文档介绍了加载 reCAPTCHA 脚本标记的最佳实践。 这些信息适用于 reCAPTCHA v2 和 v3。

异步加载 reCAPTCHA

所有版本的 reCAPTCHA 都可以异步加载。正在加载 reCAPTCHA 不会影响其识别可疑流量的能力。到期日 获享异步脚本的性能优势,加载 reCAPTCHA 或异步方式

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

异步加载 reCAPTCHA 时请注意,reCAPTCHA 不能 直到加载完成例如,以下代码可能会 断点:

<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 回调 正在加载。应在加载 reCAPTCHA 之前定义 onload 回调 脚本。

<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 (例如表单提交),通常不建议这样做。