我在网站上安装了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的加载,直到其他所有内容都加载完毕?
答案 0 :(得分:0)
恕我直言,我认为您应该使用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
祝你好运