Skip to content
This repository has been archived by the owner on Feb 6, 2024. It is now read-only.

Commit

Permalink
feat(#623): add Cory McArthur's handy injectCSS and injectJS function…
Browse files Browse the repository at this point in the history
…s to utils

Signed-off-by: peterpeterparker <david.dalbusco@outlook.com>
  • Loading branch information
peterpeterparker committed Feb 23, 2020
1 parent 3d08b91 commit a27c6ea
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
1 change: 1 addition & 0 deletions utils/utils/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export * from './utils/utils';
export * from './utils/image-utils';
export * from './utils/inject-utils';
51 changes: 51 additions & 0 deletions utils/utils/src/utils/inject-utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
export function injectJS(id: string, src: string): Promise<string> {
return new Promise<string>((resolve, reject) => {
if (!document) {
resolve();
return;
}

if (document.getElementById(id)) {
resolve('JS already loaded.');
return;
}
const script = document.createElement('script');

script.id = id;
script.async = true;
script.defer = true;
script.src = src;

script.addEventListener('load', () => resolve('JS loaded.'));

script.addEventListener('error', () => reject('Error loading script.'));
script.addEventListener('abort', () => reject('Script loading aborted.'));

document.head.appendChild(script);
});
}

export function injectCSS(id: string, src: string): Promise<string> {
return new Promise<string>((resolve, reject) => {
if (!document) {
resolve();
return;
}

if (document.getElementById(id)) {
resolve('CSS already loaded.');
return;
}

const link = document.createElement('link');
link.id = id;
link.setAttribute('rel', 'stylesheet');
link.setAttribute('href', src);

link.addEventListener('load', () => resolve('CSS loaded.'));

link.addEventListener('error', () => reject('Error loading css.'));
link.addEventListener('abort', () => reject('CSS loading aborted.'));
document.head.appendChild(link);
});
}

0 comments on commit a27c6ea

Please sign in to comment.