Skip to content
Advertisement

Implement v3 Recaptcha without recaptcha/api.js causing ‘Reduce unused JavaScript’ or ‘ Reduce the impact of third-party code’opportunities

I am able to get recaptcha to load on a website, with the async and defer tag on it.

However, when I check Pagespeed Insights against it, I see two issues:

  • Reduce the impact of third-party code. Third-party code can significantly impact load performance. Limit the number of redundant third-party providers and try to load third-party code after your page has primarily finished loading.
  • Reduce unused JavaScript and defer loading scripts until they are required to decrease bytes consumed by network activity.

The script is loaded just before the </body> tag and it looks like:

<script src="https://www.google.com/recaptcha/api.js?render=xxxxmykeyxxxx&theme=light" async defer></script>

How do I load this version of recaptcha without getting penalized on PageSpeed Insights?

#1 opportunity: Pagespeed Results

Advertisement

Answer

Regarding the first issue: reCaptcha is served with compression from google. If pagespeed is complaining about compression it is probably some other resource from your web server that is uncompressed.

Regarding the second issue: if you have set the defer or async attribute you don’t need to put the tag before </body>. Both of those attributes will not prevent rendering of the web page, even if they are loaded in the header. I don’t think your current code should trigger that check but because you use both async and defer attributes at the same time (you just need to use async and it is ok to put it in the header) just maybe it confuses pagespeed but I find that unlikely as well.

How Do I Load This Version of Recaptcha Without Getting Penalized on Pagespeed Insights?

First of all, it is not possible that the loading of just reCaptcha to cause your whole website to get a pagespeed score of 49, most likely there are other issues on your website.

Standard solution with defer attribute

To solve the “Reduce Unused JavaScript” opportunity you need to make sure the script tag that loads reCaptcha only have the defer attribute (this will prevent the script from being evaluated until the whole page has been parsed). This will improve render performance.

To actually reduce the size you would normally split the js code to only load what is needed for the web page to run but since it is a 3rd party library this is not possible.

Solution using another thread

The other option is to load the 3rd party libraries using another thread. This won’t affect the render performance, like loading js on the main thread normally does. This is useful for things like reCaptcha or Google Tag Manager, i.e. libraries that are acceptable to load async and don’t interact with other elements in the web page. This is done the easiest with a library like partytown.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement