Back to blog

Loading script asynchronously as a Promise in JavaScript

In most projects, an external library must be used (e.g. YouTube Player, Google Maps…), so the idea is to create a function to load the script asynchronously using Promise that will be resolved when the script is loaded. We can then trigger actions in the Promise and ensure that everything is executed correctly when loaded.

const loadScript = (src, async = true, type = "text/javascript") => {
  return new Promise((resolve, reject) => {
    try {
      const tag = document.createElement("script");
      const container = document.head || document.body;

      tag.type = type;
      tag.async = async;
      tag.src = src;

      tag.addEventListener("load", () => {
        resolve({ loaded: true, error: false });
      });

      tag.addEventListener("error", () => {
        reject({
          loaded: false,
          error: true,
          message: `Failed to load script with src ${src}`,
        });
      });

      container.appendChild(tag);
    } catch (error) {
      reject(error);
    }
  });
};

Let’s try to load a script

loadScript("https://www.youtube.com/iframe_api")
  .then((data) => {
    console.log("YouTube script successfully loaded", data);
  })
  .catch((error) => {
    console.error(error);
  });

That’s it!

Before you leave…
Thanks for reading! 😊