Skip to content

Commit

Permalink
feat(dom): added loadScript helper
Browse files Browse the repository at this point in the history
  • Loading branch information
kedrzu committed Jul 12, 2023
1 parent 09e516b commit 2a499ce
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/dom/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,6 @@ export * from './virtualHistory.js';
export * from './requestIdleCallback.js';
export * from './isBrowser.js';
export * from './localStorageUtils.js';
export * from './loadScript.js';
export * from './getOuterHeight.js';
export * from './scrollToTopElement.js';
23 changes: 23 additions & 0 deletions packages/dom/src/loadScript.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
const scripts: { [key: string]: Promise<void> | undefined } = {};

/**
* Loads a given script into the page.
* If script was already loaded, it won't load it again
*/
export function loadScript(url: string) {
if (scripts[url]) {
return scripts[url];
}

const scriptTag = document.createElement('script');

return new Promise<void>((resolve, reject) => {
scriptTag.src = url;
scriptTag.onload = () => resolve();
scriptTag.onerror = () => {
document.body.removeChild(scriptTag);
reject();
};
document.body.appendChild(scriptTag);
});
}

0 comments on commit 2a499ce

Please sign in to comment.