gre*_*eat 6 html javascript recaptcha deferred-loading
我在网站上安装了 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>
Run Code Online (Sandbox Code Playgroud)
并且在 head 部分添加了这个 reCaptcha js 文件:
<script defer src="https://www.google.com/recaptcha/api.js?hl=en"></script>
Run Code Online (Sandbox Code Playgroud)
即使此 js 文件使用了“defer”属性,其他相关文件仍然会加载。它们是页面速度较低的原因。
如何完全推迟此 reCaptcha 的加载,直到其他所有内容完全加载之后?
小智 1
恕我直言,我认为您应该用来IntersectionObserver观察包含验证码的元素。当元素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);
Run Code Online (Sandbox Code Playgroud)
在此处查看有关 IntersectionObserver 的更多信息: https ://developers.google.com/web/updates/2016/04/intersectionobserver
祝你好运
| 归档时间: |
|
| 查看次数: |
7913 次 |
| 最近记录: |