Skip to content

Commit

Permalink
fix: load the script via src vs inline (formbricks#3330)
Browse files Browse the repository at this point in the history
Co-authored-by: pandeymangg <[email protected]>
  • Loading branch information
loremaps and pandeymangg authored Oct 11, 2024
1 parent fca2989 commit 28dc81f
Showing 1 changed file with 14 additions and 19 deletions.
33 changes: 14 additions & 19 deletions packages/js/src/lib/load-formbricks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,33 +10,28 @@ let isInitialized = false;
// Load the SDK, return the result
const loadFormbricksSDK = async (apiHostParam: string): Promise<Result<void>> => {
if (!window.formbricks) {
const res = await fetch(`${apiHostParam}/js/formbricks.umd.cjs`);

// Failed to fetch the app package
if (!res.ok) {
return { ok: false, error: new Error(`Failed to load Formbricks SDK`) };
}

const sdkScript = await res.text();
const scriptTag = document.createElement("script");
scriptTag.innerHTML = sdkScript;
document.head.appendChild(scriptTag);
scriptTag.type = "text/javascript";
scriptTag.src = `${apiHostParam}/js/formbricks.umd.cjs`;
scriptTag.async = true;

const getFormbricks = async (): Promise<void> =>
new Promise<void>((resolve, reject) => {
const checkInterval = setInterval(() => {
if (window.formbricks) {
clearInterval(checkInterval);
resolve();
}
}, 100);

setTimeout(() => {
clearInterval(checkInterval);
const timeoutId = setTimeout(() => {
reject(new Error(`Formbricks SDK loading timed out`));
}, 10000);
scriptTag.onload = () => {
clearTimeout(timeoutId);
resolve();
};
scriptTag.onerror = () => {
clearTimeout(timeoutId);
reject(new Error(`Failed to load Formbricks SDK`));
};
});

document.head.appendChild(scriptTag);

try {
await getFormbricks();
return { ok: true, data: undefined };
Expand Down

0 comments on commit 28dc81f

Please sign in to comment.