I may be committing a typical beginner error.
Aim
I have a script named loader.js
, where I intend to provide a collection of JavaScript files that control the shape, size, and position of components.
The structure of the file is as follows:
const loadScript = (FILE_URL, async = true, type = "text/javascript") => {
return new Promise((resolve, reject) => {
try {
const scriptEle = document.createElement("script");
scriptEle.type = type;
scriptEle.async = async;
//scriptEle.async = false; // i tried with this line as well.
scriptEle.defer = true;
scriptEle.src = FILE_URL;
scriptEle.addEventListener("load", (ev) => {
resolve({ status: true });
});
scriptEle.addEventListener("error", (ev) => {
reject({
status: false,
message: `Failed to load the script ${FILE_URL}`
});
});
document.body.appendChild(scriptEle);
} catch (error) {
reject(error);
}
});
};
$(document).ready(function () {
setTimeout(proceed, 1); // wait for the document to be fully ready.
});
async function proceed() {
await loadVars(); // Load variable definitions
await loadComponents(); // load component definitions
await make_components(); // and populate them
}
function make_components() {
switch (monitorType) { // monitor type should be defined once loadvar executes (and console.log agrees)
case 1 :
addMobileHeader(wfull, hfull * 0.1);
addMobileHeroBlock(wfull, hfull* 0.7);
break;
}
}
function loadVars() {
loadScript("variables.js").then( data => {
console.log("Variables: Script loaded successfully", data);
})
.catch( err => {
console.error(err);
});
}
function loadComponents() {
loadScript("components_mobile.js").then( data => {
console.log("Components (mobilephone): Script loaded successfully _ mobile", data);
})
.catch( err => {
console.error(err);
});
loadScript("components_wide.js").then( data => {
console.log("Components (widescreen):Script loaded successfully _ wide", data);
})
.catch( err => {
console.error(err);
});
}
Issue
Naturally, make_components()
gets triggered before loadVars
finishes its execution.
Attempt at Solution
Following guidance from this response, my assumption was that since variables.js
is added first, it will run prior to the next (deferred) file, components_mobile.js
, being loaded and executed.
Only after all processes are completed, including loading and executing variables.js
and components_mobile.js
, will the make_components
function execute, finding all the definitions in the loadVars
file.
I understand that I could directly call the subsequent function within the .then
section like so:
loadScript("variables.js").then( data => {
console.log("Variables: Script loaded successfully", data);
//call next function here
})
However, this approach will result in a complex chain of functions that would be difficult for me to debug.
Question
Is there a method to compel the JS engine in Chrome/Firefox to pause until one script is entirely loaded and executed? Thank you.
EDIT: Without incorporating third-party libraries, if feasible please.