sepiariver / recaptchav2

Google's ReCaptcha V2 + V3 for MODX CMS: https://sepiariver.com/modx/recaptchav2-supports-recaptchav3/
https://sepiariver.com/
GNU General Public License v2.0
21 stars 15 forks source link

Optimize for google pagespeed #56

Open sdrenth opened 3 years ago

sdrenth commented 3 years ago

Loading the recaptcha library impacts the google pagespeed. This can be resolved by loading it deferred like this:

<script src="https://www.google.com/recaptcha/api.js?render=[[+site_key]]&hl=[[++cultureKey]]&onload=onloadCallback&render=explicit" defer></script>
<input type="hidden" name="[[+token_key]]">
<input type="hidden" name="[[+action_key]]" value="[[+form_id]]">

<script>
    function onloadCallback() {
        grecaptcha.ready(function() {
            grecaptcha.execute('[[+site_key]]', {action: '[[+form_id]]'}).then(function(token) {
                document.querySelector('[name="[[+token_key]]"]').value = token;
            });
        });
    }
</script>

Note the defer attribute on the script element and the onloadCallback function.

I think it would not be a problem to load it deferred in the default chunk.

sepiariver commented 3 years ago

Hello @sdrenth thanks for the feedback and definitely will add some documentation for this, perhaps here?

https://sepiariver.com/modx/a-guide-to-recaptcha-v3-for-modx-cms/

The default chunk is meant as that: a default starting point that can be customized for any implementation. The challenge with changing it is that some sites, which have already implemented the default, may break on update if there’s an expectation that the script will be called as-is.