Loading Files

June 08, 2024

For a web app, a <script src> at the bottom of index.html should do just fine. As the application grows, you may want to create a utility that make use of promises to lazy load script files. This way you can make order of priority, have a single app entry point, and have a clearer overview of your script files.

index.js

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

(function() {

  loadScripts([
    {
      urls: [
        'app.js',
      ],
      callback: function() {
        app.Init();
      }
    },
  ]);
  
})();

Since this will serve as the app's main entry point, we will use type module script to import the script loader function.

index.html

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

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).');
    });
  });
}

Comments

Thank You

for your visit