Fix Google ReCaptcha Asynchronous Loading Error

0, problem description

Use the following code:

html
1
2
3
<script data-instant defer src="https://recaptcha.net/recaptcha/api.js?render=SITE_KEY"></script>
<input type="hidden" name="recaptcha_response" id="recaptchaResponse" class="g-recaptcha"></input>
<script data-instant defer>grecaptcha.ready(function() {grecaptcha.execute(\''.$siteKey.'\', {action: \'social\'}).then(function(token) {var recaptchaResponse = document.getElementById(\'recaptchaResponse\');recaptchaResponse.value = token;});});</script>

DevTools console error:

Text
1
Uncaught ReferenceError: grecaptcha is not defined

1. Solution

Obviously it is a loading order problem, just remove defer, and then load it synchronously.

Asynchronous loading will not block the page, so it can be solved by using a callback function.

Principle: Use the parameter onload=callBack to call the callback function after the ReCaptcha JS file is loaded to ensure sequential execution.

Sample code:

html
1
2
3
<input type="hidden" name="recaptcha_response" id="recaptchaResponse" class="g-recaptcha"></input>
<script data-instant defer>function loadCaptcha(){grecaptcha.ready(function() {grecaptcha.execute(\''.$siteKey.'\', {action: \'social\'}).then(function( token) {var recaptchaResponse = document.getElementById(\'recaptchaResponse\');recaptchaResponse.value = token;});});};</script>
<script data-instant defer src="https://recaptcha.net/recaptcha/api.js?onload=loadCaptcha&render=SITE_KEY"></script>

Fix Google ReCaptcha Asynchronous Loading Error

https://blog.tsinbei.com/en/archives/754/

Author
Hsukqi Lee
Posted on

2023-06-22

Edited on

2023-06-22

Licensed under

CC BY-NC-ND 4.0

Comments

Name
Mail
Site
None yet