如何完全推迟加载 Google reCaptcha 直到页面完全加载完成

5

我在网站上安装了Google reCaptcha v2(复选框类型),但即使使用“defer”属性(基于PageSpeed测试),它仍会显著减缓移动设备的页面加载速度。因此,我希望完全推迟它的加载,直到页面完全加载完成。

以下是表单代码(其中安装了reCaptcha):

    <form id="sib-form" method="POST" action="https://.........." data-type="subscription">
       <input class="input" type="text" id="FIRSTNAME" name="FIRSTNAME" data-required="true">
       <input class="input" type="text" id="LASTNAME" name="LASTNAME" data-required="true">

       <script>function handleCaptchaResponse() { 
       var event = new Event('captchaChange'); document.getElementById('sib-captcha').dispatchEvent(event); 
       } </script>  

       <div class="g-recaptcha sib-visible-recaptcha" id="sib-captcha" data-sitekey="xxxxxxxxxxxxx" 
       data-callback="handleCaptchaResponse"></div>

       <button form="sib-form" type="submit">Subscribe</button>      
       <input type="text" name="email_address_check" value="" class="input--hidden">        
       <input type="hidden" name="locale" value="en">
    </form>

这个 reCaptcha 的 js 文件被添加到头部区域:

    <script defer src="https://www.google.com/recaptcha/api.js?hl=en"></script>

尽管在此js文件上使用了“defer”属性,但仍会加载其他相关文件,它们是导致页面速度变慢的原因。
如何完全推迟加载reCaptcha直到其他所有内容都加载完成?
1个回答

1

在我看来,我认为你应该使用IntersectionObserver观察包含reCAPTCHA的元素。当元素isIntersecting时,你可以将API脚本添加到body标签的末尾。

var io = new IntersectionObserver((entries) => {
    console.log(entries[0]);
    if(entries[0].isIntersecting) {
        var recaptchaScript = document.createElement('script');
        recaptchaScript.src = 'https://www.google.com/recaptcha/api.js?hl=en';
        recaptchaScript.defer = true;
        document.body.appendChild(recaptchaScript);
    }
}, {
    root: document.querySelector('.page-wrapper'),
    rootMargin: "0px",
    threshold: 1.0,
});

io.observe(document.querySelector('#sib-form'));

在此处查看有关IntersectionObserver的更多信息:https://developer.mozilla.org/zh-CN/docs/Web/API/Intersection_Observer_API

祝你好运。


谢谢您的建议。所以,我只需要删除recaptcha api脚本并将您的代码添加到body标签的末尾?我如何定义包含recaptcha的元素?还有其他需要修改的地方吗?如果您能提供更多详细信息,那将非常有帮助。 - great
谢谢您的建议。所以,我只需要删除recaptcha api脚本并将您的代码添加到body标签的末尾吗?=> 是的 我该如何定义包含recaptcha的元素?还有其他需要修改的地方吗?只需保留您的代码即可。 - An Huy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接