diff --git a/projects/ngx-turnstile/src/lib/ngx-turnstile.component.ts b/projects/ngx-turnstile/src/lib/ngx-turnstile.component.ts index 3cc5b0c..0547c33 100644 --- a/projects/ngx-turnstile/src/lib/ngx-turnstile.component.ts +++ b/projects/ngx-turnstile/src/lib/ngx-turnstile.component.ts @@ -27,6 +27,7 @@ declare global { } } +const SCRIPT_ID = 'ngx-turnstile'; const CALLBACK_NAME = 'onloadTurnstileCallback'; type SupportedVersion = '0'; @@ -83,8 +84,6 @@ export class NgxTurnstileComponent implements AfterViewInit, OnDestroy { }, }; - const script = document.createElement('script'); - window[CALLBACK_NAME] = () => { if (!this.elementRef?.nativeElement) { return; @@ -96,7 +95,14 @@ export class NgxTurnstileComponent implements AfterViewInit, OnDestroy { ); }; + if (this.scriptLoaded()) { + window[CALLBACK_NAME](); + return; + } + + const script = document.createElement('script'); script.src = `${this._getCloudflareTurnstileUrl()}?render=explicit&onload=${CALLBACK_NAME}`; + script.id = SCRIPT_ID; script.async = true; script.defer = true; document.head.appendChild(script); @@ -114,4 +120,8 @@ export class NgxTurnstileComponent implements AfterViewInit, OnDestroy { window.turnstile.remove(this.widgetId); } } + + public scriptLoaded(): boolean { + return !!document.getElementById(SCRIPT_ID); + } }