Skip to content
Advertisement

How do I force JavaScript to load in sequential order?

I’m struggling with loading JS files in sequential order, despite having looked at various other SO posts and documentation on async and defer. My code structure is as follows:

JavaScript

The contents of lang.js are as follows:

JavaScript

By my understanding, these scripts should load and execute in the order eng.js/fra.js -> task*.js -> inline, but this doesn’t seem to be the case (at least in Chrome and Firefox). How should I modify my code such that it executes in the correct order? (I would prefer not to use callbacks if possible as I don’t want to change the individual JS files too much.)

Advertisement

Answer

Without using import()

You could do something like the following:

  • Remove the <script> elements for each of the task*.js files from the document
  • Add an event listener for the load event of the inserted language script
  • Create each of the task*.js scripts inside that event listener
  • Add event listeners for the load event of each task*.js and use them to resolve a Promise, which is combined to form a global Promise
  • Wait on that global Promise in the inline script.

Doing that, the relevant parts of lang.js would become:

JavaScript

and the document would look something like:

JavaScript

None of the other scripts would need to be modified.

With this scheme:

  • lang.js is loaded first
  • eng.js/fra.js is completely loaded second
  • task1.js through task4.js are completely loaded in any order
  • inline scripts are run last

You will need to look at whether this manual deferral causes the loading to take to long; mocking this up locally has all the scripts loaded anywhere from 150ms to 450ms.

Using import()

Effectively the same as the above, but using the import() function-like keyword, lang.js becomes:

JavaScript

There are some differences in how JavaScript code is run inside something that is imported like this. The big ones are the imposition of strict mode, and the isolation of context, so you will most likely need to store any global variables explicitly onto the window variable, if you aren’t already, for the eng.js, fra.js and task*.js files.

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