Loading JavaScript, CSS, or Image Files with a Promise API

The simplest way to load an asset (JavaScript, CSS, Image) using JavaScript or TypeScript

Cesar William Alvarenga
Level Up Coding
Published in
1 min readAug 9, 2020

--

Web apps often use third-party APIs to provide a feature on a specific route of the application. Many of these APIs are heavy and don’t have a package on NPM. The usual way to add these APIs on a web app is by adding it to the main HTML file. Using this approach will affect a lot the page load time. If it’s a JavaScript file, for example, it will download, compile, and execute the script.

What if we could avoid loading these APIs on the page first load? This would help the page content load quicker, reduce overall network data usage, and lower-end devices, reduce memory usage. Well, it is possible when you load the assets asynchronously.

Loadx API

The Loadx API will help us to load the assets asynchronously with these features:

  • 🚚 Load JS, CSS or Image
  • 🚀 Cache results
  • ⏳️ Works beautifully with promise and async/await
  • 📦️ Just 400 bytes of gzipped ES3

Let’s create an example using this API:

Conclusion

Now we can load our assets only when we need them. Let’s give it a try!

--

--