How to load a script asynchronously using JavaScript

In the modern web, it is common to use 3rd-party libraries like Google Analytics, Facebook Login, etc., to integrate with those services.

In this article, you'll learn how to load an external script file asynchronously in the browser using JavaScript.

The idea is to create a function that takes the script URL as a parameter and loads it asynchronously using a promise.

The promise will be resolved successfully when the script is loaded. Otherwise, rejected.

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

      el.type = type
      el.async = async
      el.src = src

      el.addEventListener('load', () => {
        resolve({ status: true })
      })

      el.addEventListener('error', () => {
        reject({
          status: false,
          message: `Failed to load the script ${src}`
        })
      })

      container.appendChild(el)
    } catch (err) {
      reject(err)
    }
  })
}

Let's try to load Facebook JavaScript SDK:

loadScript('https://connect.facebook.net/en_US/sdk.js')
  .then(data => {
    console.log('Facebook script loaded successfully', data)
  })
  .catch(err => {
    console.error(err)
  })

That's it! You can also perform actions inside the promise once it is resolved successfully. This trick can also be used to conditionally load scripts for different environments.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.