Javascript: Synchronous imports

2nd August 2022, 03:25

Recently we’ve come across a challenge.

Well not really a challenge for normal developers, but one for developers that like to keep their development environments as barebone as possible.

The problem

Nowadays basically any browsers supports ES6 import directives and methods. Here’s a little code snippet to make sure we’re talking about the same thing:

// my-file.js

// normal direct
import MyModule from "./components/my-module.js";

// manual method
var resolved = import("./components/my-module.js");

Both of these functions work perfectly according to their specs.

But sometimes there’s a little bit more async-ness involved. For example classes that depend on external template files, or remote scripts that need to be loaded first.

In this example we’re going to assume that you, as a developer rely on a remote script because it declares an import variable MyImportVariable you need.

The solution

A way to “await” both your class and your script would be to do the following:

// my-import.js

export default new Promise((resolve, reject) => {
    let script = document.createElement("script");
    script.onload = () => {
        resolve(MyImportVariable);
    }
    script.onerror = () => {
        return resolve(false);
    }
    script.src = "some-random-domain/src/scripts/my-very-important-script.js";
});
// main.js 

// we can still use 'regular' imports
import SomeModule from "./some-other-script.js";

// but eventually we'd like to wait for this very important script to do things
let result = await (await import("./my-import.js")).default;

console.log(result);

If everything went according to plan, you should be able to see that MyImportVariable was loaded when the script was successful or returned an a boolean false.

Keep in mind that using the keyword await will suspend any further script execution which might result in performance issues or long loading times. But also keep in mind, that sometimes waiting a little bittle longer until your data is complete will also result in more complete code.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *


Recent posts

For(each) alternatives: introducing “array_map” and “array_filter”

Being a programmer, you’re probably very (very) familiar with the for and foreach loops in PHP and Javascript. So familiar […]

Read more
PHP: array_map vs array_map with callback vs foreach

So we’ve come across plenty of posts comparing / measuring performance of the PHP array_map function vs foreach. So we […]

Read more