DependencyConnector

by Konstantin Cryman

JavaScript

class DependencyConnector {
  constructor( dependencyLinks, expression ){
    this.bundle = '';
  	this.dependencyLinks = dependencyLinks || {};
  	this.expressionCallback = expression;
  	this.toloadDependencyKeys = Object.keys( this.dependencyLinks );
    this.nextDependencyLoad();
  }
  
  initBundle(){
  	return new Promise( ( resolveBundle, rejectBundle ) => {
    	try {
        const nextScriptText = this.bundle;
        const nextScriptElement = document.createElement( 'script' );
        nextScriptElement.type = 'text/javascript';
        nextScriptElement.id = 'customScriptBundle';
        nextScriptElement.text = nextScriptText;
        document.head.appendChild( nextScriptElement );
        resolveBundle();
      } catch( err ){
      		rejectBundle( err );
      }
    } );
  }
  
  nextDependencyLoad(){
  	if( this.toloadDependencyKeys.length ){
    	const nextLinkKey = this.toloadDependencyKeys.shift();
      const nextLink = this.dependencyLinks[ nextLinkKey ];
      fetch( nextLink ).then( ( data ) => {
        	data.text().then( ( resultText ) => {
          		this.bundle += '\n\n\n';
          		this.bundle += resultText;
              this.nextDependencyLoad()
          }, () => {} );
      } );
    } else {
    	this.initBundle().then( () => {
    		this.expressionCallback();
      }, ( rejectReason ) => {
      	console.err( rejectReason );
      } );
    }
  }
  
};


new DependencyConnector( {
  jQuery: 'https://code.jquery.com/jquery-3.4.1.min.js',
  THREE: 'https://cdnjs.cloudflare.com/ajax/libs/three.js/107/three.min.js'
} , () => {

  console.log( { $ } );
  
  console.log( { THREE } );

} );