Recaptcha V3 assets cause Pagespeed issues - how to defer

11,798

Solution 1

Firstly, bear in mind that 'remove unused CSS' is more of a guidance point (provided it isn't render blocking), it is indicating that it is wasted bytes (which it actually isn't if recaptcha triggers, as it then needs that CSS to render the image 'are you human check' etc.)

Although I can't give you an ideal answer as it is code you have no control over, I can give you two ways to test it's impact / whether it is actually a problem and a 'hack' to get around the load order.

Test using applied throttling

Simulated throttling can cause unexpect behaviour sometimes, which is what the Page Speed Insights website uses.

If you use the browser audit (which uses the same engine - Lighthouse) to run the tests you have an option to change the throttling from simulated to applied.

Although your score will change (applied throttling is less forgiving than simulated throttling), you get a much more realistic order of events as the latency and slowdown is 'real' vs making best guesses based on loading the page at full speed and applying formula's to guess load times.

Open Dev Tools in Chrome (F12) -> Audits -> Throttling -> set to Applied Slow 4G, 4x CPU Slowdown. -> Run Audits.

See if the problem persists when using this way of assessing page speed.

If it does, a workaround / test for real world performance is as follows:-

Force the script to load after an amount of time (the hacky way!)

This is not an ideal solution but it is good for testing and as a last resort if it does actually slow down your website key load times.

Insert the script dynamically after 5 seconds.

(please note the below code is untested and is likely to not work, it is for illustration only to point you in the right direction. It is highly probable that you don't need the script.onload section and can include that normally)

setTimeout(function(){
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.onload = function() {
        grecaptcha.ready(function() {
            grecaptcha.execute('_reCAPTCHA_site_key_', {action: 'homepage'}).then(function(token) {
               ...
            });
        });
    }
    script.src = "https://www.google.com/recaptcha/api.js?render=_reCAPTCHA_site_key";
    head.appendChild(script);
 }, 5000);

Solution 2

We can use IntersectionObserver to defer Recaptcha script.

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);
Share:
11,798

Related videos on Youtube

laserslasers
Author by

laserslasers

Updated on November 01, 2022

Comments

  • laserslasers
    laserslasers over 1 year

    We're currently using Google Recaptcha V3 across the public-facing portions of our site - while doing Pagespeed Insights performance testing (Mobile), Google themselves is reporting unused/undeferred CSS as a problem on their own Recaptcha css file:

    enter image description here

    Full resource address is: https://www.gstatic.com/recaptcha/releases/[...]/styles__ltr.css (so it is clearly coming from a subsequent Google Recaptcha script request)

    We are including the original Google recaptcha script with the 'defer' attribute set - not sure what else we can do to cause this css to be deferred such that Pagespeed does not complain about it. Can't find any documentation on the Google Recaptcha site itself to help with this issue.

    Does anyone know how to defer this CSS to improve page load time? Not sure if this is somehow a Mobile specific issue, as Pagespeed doesn't report it at all on Desktop.

  • user1620090
    user1620090 over 3 years
    Your solution works well but less hacky if wrapped in a function and called on focus for instance. $('#newsletter_register .form-control').focus(function(){ if ( captchaLoaded ==false) { loadCaptcha(); } });
  • Graham Ritchie
    Graham Ritchie over 3 years
    yes, the only reason I would choose this option over loading on focus is if someone is on 3G there may be an issue with the script taking a while to load which can upset it when it is trying to work out if you are a human. Either way it is a hacky way to solve the issue but your way should be fine in 99% of cases.