正在加载 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 = {};
  }
  grecaptcha.ready = function(cb){
    if(typeof grecaptcha === 'undefined') {
      // 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);
    } else {
      cb();
    }
  }

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

作为替代方案,使用 v2 API 的网站可能会发现使用 onload 回调很有用;onload 回调会在 reCAPTCHA 完成加载后执行。应在加载 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,强烈建议包含 reCAPTCHA 的 preconnect 资源提示。这样可以最大限度地缩短脚本下载阻止解析器的时间。

使用资源提示

在文档的 <head> 中添加以下资源提示可以减少传送 reCAPTCHA 使用的资源所需的时间。preconnect 资源提示会指示浏览器与第三方来源建立早期连接。

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

延迟加载

一般来说,reCAPTCHA 对网页的上下文越多,就越能准确地判断用户操作是否合法。在使用不依赖于用户质询的 reCAPTCHA 版本时尤其如此。因此,通常不建议在发生特定受限操作(例如表单提交)时加载 reCAPTCHA。