Loading Script Files

December 11, 2024

Files

js/
  main-component.js
index.html
index.js
script-loader.js

Source Code

index.html

<script src="index.js" type="module"></script>

index.js

import { loadScripts } from './script-loader.js';

(function() {

  loadScripts([
    {
      urls: [
        'js/main-component.js',
      ],
      callback: function() {
        compoMain.Init();
      }
    },
  ]);
  
})();

script-loader.js

export { loadScripts };

function loadScripts(components) {
  let loadIndex = -1;
  loadComponents(components, loadIndex);
}

function loadComponents(components, index) {
  if (index >= 0 && components[index].callback) {
    components[index].callback();
  }
  index++;
  if (index < components.length) {
    loadExternalFiles(components[index].urls).then(() => {
      loadComponents(components, index);
    });
  }
}

function requireExternalFiles(url) {
  return new Promise((resolve, reject) => {
    let el;
    el = document.createElement('script');
    el.setAttribute('src', url);
    el.onload = () => resolve(url);
    el.onerror = () => reject(url);
    document.head.appendChild(el);
  });
}

function loadExternalFiles(URLs) {
  return new Promise(resolve => {
    let bundleURL = [];
    for (let URL of URLs)
      bundleURL.push(requireExternalFiles(URL));
    Promise.all(bundleURL).then(() => {
      resolve();
    }).catch(error => {
      console.log(error);
      console.log('Could not load one or more required file(s).');
    });
  });
}

js/main-component.js

let compoMain = (function () {
	// # self
	let SELF = {
		Init,
	};

	// # function

	function Init() {}

	return SELF;
})();

Comments

Thank You

for your visit