Dynamically loading JavaScript synchronously

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

    You can't and shouldn't perform server operations synchronously for obvious reasons. What you can do, though, is to have an event handler telling you when the script is loaded:

    tag.onreadystatechange = function() { if (this.readyState == 'complete' || this.readyState == 'loaded') this.onload({ target: this }); };
    
    tag.onload = function(load) {/*init code here*/}
    

    onreadystatechange delegation is, from memory, a workaround for IE, which has patchy support for onload.

提交回复
热议问题