/**
 * Creates new async script tag by id and src
 */ const createAsyncScript = ( id , src ) : HTMLScriptElement => { const script = document . createElement ( 'script' ) ; script . id = id ; script . async = true ; script . src = src ; return script ; } ; param id param src export function loadScript ( id , src ) { return new Promise ( ( resolve , reject ) => { const script = ( document . getElementById ( id ) || createAsyncScript ( id , src ) ) as HTMLScriptElement ; const state = script . getAttribute ( 'state' ) ; switch ( state ) { case 'success' : resolve ( new Event ( 'load' ) ) ; break ; case 'error' : reject ( new Event ( 'error' ) ) ; break ; default : script . addEventListener ( 'load' , ( e ) => { script . setAttribute ( 'state' , 'success' ) ; resolve ( e ) ; } ) ; script . addEventListener ( 'error' , ( e ) => { script . setAttribute ( 'state' , 'error' ) ; reject ( e ) ; } ) ; } if ( ! script . parentNode ) { const firstScriptTag = document . querySelector ( 'script' ) || document . querySelector ( 'head title' ) ; if ( firstScriptTag && firstScriptTag . parentNode ) { firstScriptTag . parentNode . insertBefore ( script , firstScriptTag ) ; } else { reject ( 'Page document structure is incorrect' ) ; } } } ) ; }