Magento 2 Lazy load google recaptcha js

By | October 30, 2023
Spread the love

Magento 2 is a popular e-commerce platform, and like many websites, it can experience issues with Core Web Vitals, which are a set of performance metrics that Google uses to measure the user experience on web pages. Core Web Vitals include:

Google recaptcha have important role to fix it.  Follow below code to lazy load and improve google score by 20 %

Go to app\design\frontend\{theme}\{subdir}\Magento_ReCaptchaFrontendUi\web\js and open reCaptchaScriptLoader.js.

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
define(['jquery'], function($) {
    'use strict';

    var scriptTagAdded = false;

    return {
        /**
         * Add script tag. Script tag should be added once
         */
        addReCaptchaScriptTag: function() {
            console.log("bind");

            $(document).ready(function() {
                var inputBox = $('input[type="email"],input[type="text"]');
                $(inputBox).click(function() {
                    console.log("bind click");

                    var element, scriptTag;

                    if (!scriptTagAdded) {
                        console.log("bind load");

                        element = document.createElement('script');
                        scriptTag = document.getElementsByTagName('script')[0];

                        element.async = true;
                        element.src = 'https://www.google.com/recaptcha/api.js' +
                            '?onload=globalOnRecaptchaOnLoadCallback&render=explicit';

                        scriptTag.parentNode.insertBefore(element, scriptTag);
                        scriptTagAdded = true;

                        $(inputBox).unbind();
                    }
                });
            });
        }
    };
});

Replace code in theme folder. Now js will be load on demand on click on input box field only.

 

  1. Largest Contentful Paint (LCP): This measures the loading performance of a page. To improve LCP in Magento 2, you can optimize images, use a content delivery network (CDN), and leverage browser caching.
  2. First Input Delay (FID): FID evaluates the interactivity of a page. Slow FID can be caused by long JavaScript execution times. To address this, you should minimize and defer non-essential JavaScript, use web workers, and avoid long tasks.
  3. Cumulative Layout Shift (CLS): CLS assesses the visual stability of a page. In Magento 2, CLS can be impacted by elements moving around while the page loads. To fix CLS issues, make sure to specify image dimensions, avoid adding or resizing content dynamically, and use proper CSS for layout.