import { Injectable , NgZone } from '@angular/core' ; @ Injectable ( ) export class ScriptService { constructor ( protected zone ) { } registerScript ( url , globalVar , onReady ) { const existingGlobalVar = ( window as any ) [ globalVar ] ; if ( existingGlobalVar ) { this . zone . run ( ( ) => { onReady ( existingGlobalVar ) ; } ) ; return ; } const scriptElem = document . createElement ( 'script' ) ; scriptElem . id = this . getElemId ( globalVar ) ; scriptElem . innerHTML = '' ; scriptElem . onload = ( ) => { this . zone . run ( ( ) => { onReady ( ( window as any ) [ globalVar ] ) ; } ) ; } ; scriptElem . src = url ; scriptElem . async = true ; scriptElem . defer = true ; document . getElementsByTagName ( 'head' ) [ 0 ] . appendChild ( scriptElem ) ; } cleanup ( globalVar ) { const scriptElem = document . getElementById ( this . getElemId ( globalVar ) ) ; if ( scriptElem ) { scriptElem . remove ( ) ; } } private getElemId ( globalVar ) { return `ngx-paypal-script-elem-${ globalVar }` ; } }