Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Idea: possibly avoid setTimeout and waitForScriptToLoad #567

Open
0biWanKenobi opened this issue Sep 16, 2022 · 0 comments
Open

Idea: possibly avoid setTimeout and waitForScriptToLoad #567

0biWanKenobi opened this issue Sep 16, 2022 · 0 comments

Comments

@0biWanKenobi
Copy link

So while looking at the code, I noticed that after the api.js script has been loaded, a 25ms looping setTimeout starts, waiting for the grecaptcha instance to be available. Now, in most cases the instance is already available and the timeout never starts, so that's good. But I was wondering if we could skip all of that logic alltogether, and rely on the onload callback that we can provide to ReCaptcha.

Code snippet below, I'm testing it with patch-package and it seems to work flawlessly. Wdyt, worth a PR?

// inside ReCaptchaLoader.prototype.loadScript 
// [...]

if(renderParameters.onload) {
  renderParameters.onload = undefined;
}

var parametersQuery = this.buildQueryString(renderParameters);
scriptElement.src = scriptBase + '?render=explicit&onload=onRecaptchaLoad' + parametersQuery;


var _onRecaptchaLoad = (callback, useEnterprise) => {
  if (useEnterprise) {
    window.grecaptcha.enterprise.ready(function () {
        callback();
    });
  }
  else {
      window.grecaptcha.ready(function () {
          callback();
      });
  }
}

return new Promise(function (resolve, reject) {
    const onSuccess = () => {
      resolve(scriptElement)
      window.onRecaptchaLoad = undefined
    }
    window.onRecaptchaLoad = () => {
      _onRecaptchaLoad(onSuccess, useEnterprise)
    }
    scriptElement.onerror = function (error) {
        ReCaptchaLoader.setLoadingState(ELoadingState.NOT_LOADED);
        reject(error);
        window.onRecaptchaLoad = undefined
    };
    document.head.appendChild(scriptElement);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant