Skip to content
Advertisement

Dynamically load Javascript file one at a time

I am creating a loader. Since I use Firebase, I need to load the specific script files dynamically in the exact order. Here are the code in my HTML files. JsPack.js is a loader that will load specific scripts one at a time.

JavaScript

And here is my current jsPack.js file. This works perfectly in the exact order. However, it cannot load only specific scripts, and just loads all scripts at once.

JavaScript

Now, I have changed it into something like this.

JavaScript

It should have been working. However, all the scripts are loaded at once and the 2nd script cannot get the objects from the 1st. Right now, I do not know what is the problem with my codes. The page loads very fast , proving that those scripts are loaded at the same time. The 2nd script also returns error since it cannot get the objects from the 1st script. However, the console.log states that the scripts are loaded one at a time, which really confuses me.

Console

Please respond if you know what is the problem with my codes. Thank you in advance.


Update: onload() with async works perfectly. Thank you very much. I did not expect we could put async inside script. With this I will not have to use Promise at all.

enter image description here

Advertisement

Answer

Use the script async attribute

Seems like the problem could be solved easily by setting the async attribute to false. This way the scripts load in order and Firebase works. If set to true then the scripts can load in unpredictable order based on size, location, etc. And Firebase may fail because firebase-app.js must always be loaded first. And in fact, you’ll see those errors if you set async = true in the snippet.

JavaScript

Run the snippet to see the scripts load in order:

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement