Created
July 22, 2018 09:34
Revisions
-
0xHexE created this gist
Jul 22, 2018 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,62 @@ import { Injectable } from '@angular/core'; @Injectable() export class ScriptLoaderService { constructor() { } loadScript(url: string) { return this.load(url, 'script'); } loadStyle(url: string) { return this.load(url, 'stylesheet'); } private load(url: string, type: 'script' | 'stylesheet') { return new Promise((resolve, error) => { let node; let isScript: HTMLElement; switch (type) { case 'script': isScript = Array.from(document.getElementsByTagName('script')) .find(res => res.getAttribute('src') != null && res.getAttribute('src').includes(url)); if (!isScript) { node = document.createElement('script'); node.type = 'text/javascript'; node.src = url; } break; case 'stylesheet': isScript = Array.from(document.getElementsByTagName('link')) .find(res => res.getAttribute('href') != null && res.getAttribute('href').includes(url)); if (!isScript) { node = document.createElement('link'); node.rel = 'stylesheet'; node.href = url; } } if (isScript && isScript.classList.contains('file-loaded-script-loader')) { return resolve(); } else if (isScript) { return isScript.onload = () => { resolve(); } } node.async = false; node.charset = 'utf-8'; document.getElementsByTagName('head')[0].appendChild(node); node.onload = () => { node.classList.add('file-loaded-script-loader'); resolve(); }; node.onerror = () => { error(); } }); } }