Created
February 28, 2021 09:58
-
-
Save lazypanda-instance/d06abfa4a6d06e28f06376114d81e2bc to your computer and use it in GitHub Desktop.
add external script in angular
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'; | |
import { ScriptStore } from './script-loader'; | |
declare var document: any; | |
@Injectable({ | |
providedIn: 'root' | |
}) | |
export class ScriptService { | |
private scripts: any = {}; | |
constructor() { | |
ScriptStore.forEach((script: any) => { | |
this.scripts[script.name] = { | |
loaded: false, | |
src: script.src | |
}; | |
}); | |
} | |
load(idValue: string, ...scripts: string[]) { | |
const promises: any[] = []; | |
scripts.forEach((script) => promises.push(this.loadScript(script, idValue))); | |
return Promise.all(promises); | |
} | |
loadScript(name: string, idValue: string) { | |
return new Promise((resolve, reject) => { | |
const script = document.createElement('script'); | |
script.type = 'text/javascript'; | |
script.id = 'ads'; | |
script.src = this.scripts[name].src; | |
script.setAttribute('data-name', idValue); | |
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); | |
}); | |
} | |
} |
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 { environment } from 'src/environments/environment'; | |
interface Scripts { | |
name: string; | |
src: string; | |
} | |
export const ScriptStore: Scripts[] = [ | |
{ | |
name: 'google-ads', | |
src: `${environment.webAppURL}assets/ad-script/ga-lazy.js` | |
} | |
]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment