From 59c7617662c4a0faac919775b1ac38b9e283561c Mon Sep 17 00:00:00 2001 From: Arpan Sarkar Date: Tue, 29 Nov 2022 10:45:15 +0530 Subject: [PATCH] lazy load script from cdn --- public/index.html | 34 +++++++++++++++------------------- src/frames/Frames.tsx | 22 +++++++++++++++++++--- 2 files changed, 34 insertions(+), 22 deletions(-) diff --git a/public/index.html b/public/index.html index a71675c..46a0133 100755 --- a/public/index.html +++ b/public/index.html @@ -1,24 +1,20 @@ + + + + + + + - - - - - - - + - + React App + - React App - - - - -
- - - - - \ No newline at end of file + + +
+ + diff --git a/src/frames/Frames.tsx b/src/frames/Frames.tsx index 6d5600d..ba8e021 100755 --- a/src/frames/Frames.tsx +++ b/src/frames/Frames.tsx @@ -20,9 +20,14 @@ export class Frames extends Component { componentDidMount(): void { const existingScript = document.querySelector(`script[src$="${CDN}"]`); if (!existingScript) { - console.error( - `Checkout.com CDN not present. Perhaps you forgot to add to your index.html file.` - ); + (async () => { + try { + await this.loadScript(); + this.initializeFrames(); + } catch (error: any) { + throw new Error(error); + } + })(); } else { this.initializeFrames(); } @@ -41,6 +46,17 @@ export class Frames extends Component { return true; } + loadScript = () => { + if (typeof window === 'undefined') return; // Don't execute this function if it's rendering on server side + return new Promise((resolve, reject) => { + const scriptTag = document.createElement('script'); + scriptTag.src = CDN; + scriptTag.onload = (ev) => resolve(ev); + scriptTag.onerror = (err) => reject(err); + document.body.appendChild(scriptTag); + }); + }; + initializeFrames = () => { let config = { publicKey: this.props.config.publicKey,