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.