Dynamically loading JavaScript synchronously

后端 未结 18 2279
小蘑菇
小蘑菇 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:41

    There is only one way to synchronously load and execute a script resource, and that is using a synchronous XHR

    This is an example of how to do this

    // get some kind of XMLHttpRequest
    var xhrObj = createXMLHTTPObject();
    // open and send a synchronous request
    xhrObj.open('GET', "script.js", false);
    xhrObj.send('');
    // add the returned content to a newly created script tag
    var se = document.createElement('script');
    se.type = "text/javascript";
    se.text = xhrObj.responseText;
    document.getElementsByTagName('head')[0].appendChild(se);
    

    But you shouldn't in general use synchronous requests as this will block everything else. But that being said, there are of course scenarios where this is appropriate.

    I would probably refactor the containing function into an asynchronous pattern though using an onload handler.

提交回复
热议问题