import { loadCss } from './utils/css' ; import utils from './utils/index' ; import { getCdnUrl } from './utils/url' ; let defaultOptions = { } ; function createScript ( url ) { const script = document . createElement ( 'script' ) ; script . type = 'text/javascript' ; script . src = url ; script . setAttribute ( 'data-esri-loader' , 'loading' ) ; return script ; } function handleScriptLoad ( script , callback , errback ? ) { let onScriptError ; if ( errback ) { onScriptError = handleScriptError ( script , errback ) ; } const onScriptLoad = ( ) => { callback ( script ) ; script . removeEventListener ( 'load' , onScriptLoad , false ) ; if ( onScriptError ) { script . removeEventListener ( 'error' , onScriptError , false ) ; } } ; script . addEventListener ( 'load' , onScriptLoad , false ) ; } function handleScriptError ( script , callback ) { const onScriptError = ( e ) => { callback ( e . error || new Error ( `There was an error attempting to load ${ script . src }` ) ) ; script . removeEventListener ( 'error' , onScriptError , false ) ; } ; script . addEventListener ( 'error' , onScriptError , false ) ; return onScriptError ; } export interface ILoadScriptOptions { version ? : string ; url ? : string ; css ? : string | boolean ; insertCssBefore ? : string ; } export function setDefaultOptions ( options = { } ) { defaultOptions = options ; } export function getScript ( ) { return document . querySelector ( 'script[data-esri-loader]' ) as HTMLScriptElement ; } export function isLoaded ( ) { const globalRequire = window [ 'require' ] ; return globalRequire && globalRequire . on ; } export function loadScript ( options = { } ) { const opts = { } ; [ defaultOptions , options ] . forEach ( ( obj ) => { for ( const prop in obj ) { if ( Object . prototype . hasOwnProperty . call ( obj , prop ) ) { opts [ prop ] = obj [ prop ] ; } } } ) ; const version = opts . version ; const url = opts . url || getCdnUrl ( version ) ; return new utils . Promise ( ( resolve , reject ) => { let script = getScript ( ) ; if ( script ) { const src = script . getAttribute ( 'src' ) ; if ( src !== url ) { reject ( new Error ( `The ArcGIS API for JavaScript is already loaded (${ src }).` ) ) ; } else { if ( isLoaded ( ) ) { resolve ( script ) ; } else { handleScriptLoad ( script , resolve , reject ) ; } } } else { if ( isLoaded ( ) ) { reject ( new Error ( `The ArcGIS API for JavaScript is already loaded.` ) ) ; } else { const css = opts . css ; if ( css ) { const useVersion = css === true ; loadCss ( useVersion ? version : ( css as string ) , opts . insertCssBefore ) ; } script = createScript ( url ) ; handleScriptLoad ( script , ( ) => { script . setAttribute ( 'data-esri-loader' , 'loaded' ) ; resolve ( script ) ; } , reject ) ; document . body . appendChild ( script ) ; } } } ) ; }