0, problem description
Use the following code:
1 | <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:
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:
1 | <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
Comments