Dynamically load a JavaScript file

后端 未结 28 3357
说谎
说谎 2020-11-22 06:56

How can you reliably and dynamically load a JavaScript file? This will can be used to implement a module or component that when \'initialized\' the component will dynamical

28条回答
  •  温柔的废话
    2020-11-22 07:36

    With Promises you can simplify it like this. Loader function:

      const loadCDN = src =>
        new Promise((resolve, reject) => {
          if (document.querySelector(`head > script[src="${src}"]`) !== null) return resolve()
          const script = document.createElement("script")
          script.src = src
          script.async = true
          document.head.appendChild(script)
          script.onload = resolve
          script.onerror = reject
        })
    

    Usage (async/await):

    await loadCDN("https://.../script.js")
    

    Usage (Promise):

    loadCDN("https://.../script.js").then(res => {}).catch(err => {})
    

    NOTE: there was one similar solution but it doesn't check if the script is already loaded and loads the script each time. This one checks src property.

提交回复
热议问题