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

问题描述 投票:0回答:1

我在网站上安装了 Google reCaptcha v2(复选框类型)。但即使使用“延迟”属性(基于页面速度测试),它也会显着减慢移动设备上的页面加载速度。所以,我想完全推迟其加载,直到页面完全加载之后。

这就是表单代码(安装 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文件被添加到head部分:

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

即使这个js文件使用了'defer'属性,其他相关文件仍然会被加载。它们是页面速度较低的原因。

如何完全推迟此 reCaptcha 的加载,直到其他所有内容完全加载之后?

javascript html recaptcha deferred-loading
1个回答
1
投票

恕我直言,我认为你应该使用 IntersectionObserver 来观察包含 recaptcha 的元素。当元素

isIntersecting
时,可以在body标签末尾添加api脚本

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(initForm);

在此处查看有关 IntersectionObserver 的更多信息: https://developers.google.com/web/updates/2016/04/intersectionobserver

祝你好运

© www.soinside.com 2019 - 2024. All rights reserved.