Recaptcha fails on optimized sites (grecaptcha is not defined) Solution Included
-
When a WordPress theme is configured to defer all JS for performance the reCaptcha scripts fail. The error
grecaptcha is not defined
is shown and it’s caused by a script that is inserted by reCaptcha module in the page footer.Solutions I’ve seen so far is to:
1. Remove deferment from reCaptcha scripts. This is not an ideal solution as it affects performance in a negative way and gives reCaptcha priority over other scripts, which it should not have.
2. Modify the plugin itself to defer scripts. This is again a bad recommendation as it would require web developer to modify the plugin after each upgrade.Proposed Solution
Dear plugin authors.
We appreciate all your hard effort on this plugin so far and know you are very busy. But please incorporate the following solution into the new version of the plugin so all site can continue to use the plugin and have it render in an optimal way.I propose a solution to update the JavaScript code inserted in
/modules/recaptcha.php
in functionwpcf7_recaptcha_onload_script()
to render JavaScript as follows:document.addEventListener("DOMContentLoaded", function(event) { ( function( grecaptcha, sitekey, actions ) { ... } )( grecaptcha, '<?php echo esc_js( $service->get_sitekey() ); ?>', <?php echo json_encode( $actions ), "\n"; ?> ); });
The addition is a wrapper around the code to set it to execute not immediately but after the document has finished rendering. So far I’m not seeing any reason why a reCaptcha code should or would want to be executed or rendered before the document is ready.
Thank you for your consideration of incorporating this fix into future revisions of this wonderful plugin.
- The topic ‘Recaptcha fails on optimized sites (grecaptcha is not defined) Solution Included’ is closed to new replies.