Loading Script Files
A starter code to load JavaScript files in queue for a small JavaScript app.
Introduction
There are times when one would prefer loading JavaScript files using <script>
tags rather than import
/export
. This starter code provides a simple code alternative to a full featured script loading library, for your small web app.
In this code, the main entry point will be a module and the rest are a non-module scripts.
import { loadScripts } from './js/infrastructure/script-loader.js';
loadScripts([
{
urls: [
"js/main-component.js",
"js/ui.js",
],
callback: () => {
console.log('App ready.');
},
},
{
urls: [
"js/components/a-component.js",
"js/components/b-component.js",
],
},
]);
The reason, is that one may want to import the URLs into a build script, e.g. to build a cache manifest file for Progressive Web App (PWA).
Takeaway Code
Recommended project directory tree:
.
├── js/
│ └── infrastructure/
│ └── script-loader.js
├── index.html
└── index.js
js/infrastructure/script-loader.js
Repository: script-loader.js
index.html
<script src="index.js" type="module"></script>
index.js
import { loadScripts } from './js/infrastructure/script-loader.js';
loadScripts([
{
urls: [
// "js/main-component.js",
// "js/ui.js",
],
callback: () => {
console.log('App ready.');
},
},
]);
Open comments page