Dynamically loading JavaScript synchronously

后端 未结 18 2271
小蘑菇
小蘑菇 2020-11-27 13:55

I\'m using the module pattern, one of the things I want to do is dynamically include an external JavaScript file, execute the file, and then use the functions/variables in t

18条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-27 14:54

    the accepted answer is not correct:

    the script.async = false; directive only means that html parsing will be paused during script execution. this does not guarantee in which order javascript code will run. see https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/loading-third-party-javascript/

    the easiest and most elegant solution which was yet to be mentioned here is using promises, like so:

        function loadScript(url) {
          return new Promise((resolve, reject) => {
            var script = document.createElement('script')
            script.src = url
            script.onload = () => {
              resolve()
            }
            script.onerror = () => {
              reject('cannot load script '+ url)
            }
            document.body.appendChild(script)
          })
        }
    

    and then when you want to execute scripts in order:

            loadScript('myfirstscript.js').then(() => {
              console.log('first script ran');
              loadScript('index.js').then(() => {
                console.log('second script ran');
              })
            })
    

提交回复
热议问题