4

I'm using react-google-recaptcha-v3 in my React project. I have used defer prop attribute but it is still slow.

enter image description here

How can I improve the speed with the use of this plugin? It only affects significantly on mobile view. Is there a way to not load the form portion during page load? Or any better solution for this issue?

<GoogleReCaptchaProvider
  reCaptchaKey="KEY_HERE"
  scriptProps={{
    defer: true,
  }}
>
//Form here
</GoogleRecaptchaProvider>
Ferran Buireu
  • 28,630
  • 6
  • 39
  • 67
Samuel L.
  • 61
  • 5

1 Answers1

0

I had this same issue and I managed to fix it by wrapping the provider on my custom GoogleRecaptchaWrapper component, so the component will only inject the recaptcha.js after some sort of interaction happens in the page (and not on page load). Here is the code:

const RECAPTCHA_EVENT_LIST = ["mousemove", "mousedown", "keydown", "touchstart"]

export const GoogleRecaptchaWrapper = props => {
  const { children } = props
  const [recaptchaProps] = useState({ defer: true })
  const [recaptchaNeeded, setRecaptchaNeeded] = useState(false)

  const initRecaptcha = e => {
    RECAPTCHA_EVENT_LIST.forEach(ev =>
      document.removeEventListener(ev, initRecaptcha)
    )
    setRecaptchaNeeded(true)
  }

  ifBrowser(() => {
    RECAPTCHA_EVENT_LIST.forEach(ev =>
      document.addEventListener(ev, initRecaptcha)
    )
  })

  const wrapperProps = recaptchaNeeded
    ? {
        reCaptchaKey: AppConfig.recaptchaSiteKey,
        scriptProps: recaptchaProps
      }
    : {}

  return (
    <GoogleReCaptchaProvider {...wrapperProps}>
      {children}
    </GoogleReCaptchaProvider>
  )
}

As I say, this only injects the JS when recaptchaNeeded is true. I hope it helps!

dcapilla
  • 171
  • 6