Last active
December 18, 2020 15:33
-
-
Save zainzafar90/1f58a4a04ac17fcf8e7424a053620822 to your computer and use it in GitHub Desktop.
Angular Service to load scripts on demand dynamically
This file contains 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'; | |
interface Scripts { | |
name: string; | |
src: string; | |
} | |
export const ScriptStore: Scripts[] = [ | |
{ name: 'chartjs', src: 'https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.min.js' }, | |
{ name: 'random-gen', src: '../../../assets/js/random-num-generator.js' } | |
]; | |
declare var document: any; | |
@Injectable() | |
export class DynamicScriptLoaderService { | |
private scripts: any = {}; | |
constructor() { | |
ScriptStore.forEach((script: any) => { | |
this.scripts[script.name] = { | |
loaded: false, | |
src: script.src | |
}; | |
}); | |
} | |
load(...scripts: string[]) { | |
const promises: any[] = []; | |
scripts.forEach((script) => promises.push(this.loadScript(script))); | |
return Promise.all(promises); | |
} | |
loadScript(name: string) { | |
return new Promise((resolve, reject) => { | |
if (!this.scripts[name].loaded) { | |
//load script | |
let script = document.createElement('script'); | |
script.type = 'text/javascript'; | |
script.src = this.scripts[name].src; | |
if (script.readyState) { //IE | |
script.onreadystatechange = () => { | |
if (script.readyState === "loaded" || script.readyState === "complete") { | |
script.onreadystatechange = null; | |
this.scripts[name].loaded = true; | |
resolve({script: name, loaded: true, status: 'Loaded'}); | |
} | |
}; | |
} else { //Others | |
script.onload = () => { | |
this.scripts[name].loaded = true; | |
resolve({script: name, loaded: true, status: 'Loaded'}); | |
}; | |
} | |
script.onerror = (error: any) => resolve({script: name, loaded: false, status: 'Loaded'}); | |
document.getElementsByTagName('head')[0].appendChild(script); | |
} else { | |
resolve({ script: name, loaded: true, status: 'Already Loaded' }); | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi @zainzafar90, what license would this example code be? It's referenced in https://medium.com/better-programming/angular-load-external-javascript-file-dynamically-3d14dde815cb which does not specify a license either. Thanks!