Skip to content

Idea: possibly avoid setTimeout and waitForScriptToLoad #567

Description

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);
});

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions