Dynamically loading JavaScript synchronously

后端 未结 18 2330
小蘑菇
小蘑菇 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-27 14:51

    The accepted answer is NOT correct.

    Loading a file synchronously is not the same as executing the file synchronously - which is what the OP requested.

    The accepted answer loads the file sync, but does nothing more than append a script tag to the DOM. Just because appendChild() has returned does not in anyway guarantee that the script has finished executing and it's members are initialised for use.

    The only (see caveat) way to achieve the OPs question is to sync load the script over XHR as stated, then read as text and pass into either eval() or a new Function() call and wait for that function to return. This is the only way to guarantee the script is loaded AND executed synchronously.

    I make no comment as to whether this is a wise thing to do either from a UI or security perspective, but there are certainly use cases that justify a sync load & execute.

    Caveat: Unless you're using web workers in which case just call loadScripts();

提交回复
热议问题