While reCAPTCHA is useful, it can also impact website speed, particularly the Largest Contentful Paint (LCP), a critical web vitals metric.
You can lazy load reCAPTCHA after the user interacts with the form, so you won’t be compromising your web page performance.
Lazy Loading reCAPTCHA
Given the nature of reCAPTCHA, where it isn’t always immediately needed, it’s an excellent candidate for lazy loading.
Let’s consider a typical use case: a user visits a contact form on a website. They’ll first focus on input fields (like filling out their name, email, or message) before they interact with the reCAPTCHA challenge.
Hence, rather than loading reCAPTCHA immediately when the page loads, we can defer its loading until the user starts interacting with the form.
Implementation
Here’s a step-by-step guide on lazy loading reCAPTCHA:
- Remove the default reCAPTCHA script in the JS code from the webpage.
- Add an event listener on a relevant form field (like a textarea or input). When the user focuses on or interacts with this element, load the reCAPTCHA library.
let reCaptchaLoaded = false;
document.getElementById("your-input-field").addEventListener("focus", function() {
if (!reCaptchaLoaded) {
var recaptchaScript = document.createElement('script');
recaptchaScript.setAttribute('src', 'https://www.google.com/recaptcha/api.js');
document.body.appendChild(recaptchaScript);
reCaptchaLoaded = true;
}
});
With these lines of JavaScript, reCAPTCHA will load only when the user starts interacting with the form.
Keep in mind that this lazy reCaptch loading on slower connections might notice a slight delay between interacting with the form and reCAPTCHA being ready.