How to dynamically load and use/call a JavaScript file?

前端 未结 4 1148
萌比男神i
萌比男神i 2020-11-30 13:29

I need to dynamically load a JavaScript file and then access its content.

File test.js

test = function () {
    var pub = {}
    pub.def         


        
4条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-30 13:45

    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 and doesn't add script tag if already loaded. 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 => {})
    

提交回复
热议问题