Created
July 22, 2018 09:34
-
-
Save 0xHexE/867ff31e85d1df5341d449bfa2c0a76f to your computer and use it in GitHub Desktop.
Load dynamically file in the angular using service
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 characters
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(); | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment