Is there a known workaround for IE9's executio

2020-03-26 03:45发布

I am sure I don't fully understand this problem, but it seems that we are seeing strange behavior on IE9 on my project, somehow related to out-of-order execution of JavaScript that has been injected via calls to document.write, e.g.:

document.write('<scr'+'ipt type="text/javascript" src="'+file1+'"></src'+'ipt>');
document.write('<scr'+'ipt type="text/javascript" src="'+file2+'"></src'+'ipt>');
document.write('<scr'+'ipt type="text/javascript" src="'+file3+'"></src'+'ipt>');

My limited Google research suggests that IE9 will execute scripts injected in this manner in a different order from other browsers (notably, Firefox and Chrome). Is there a better way to achieve what we're going for here, which will ensure the same execution order by all browsers?

I take that back: we don't really care about all browsers, just Chrome and IE9.

4条回答
地球回转人心会变
2楼-- · 2020-03-26 04:08

So the advantage of writing script tags this way is that they are loaded asynchronously. I don't know about browser nuances about exactly how this is done but I would have thought they would be executed when they're downloaded, in no specific order. Similar to the behaviour of the HTML5 async attribute.

There's another HTML5 attribute defer which instead makes scripts execute in order, but in a non blocking way. You could try adding that into your generated <script> tags. IE9 partially honours it.

查看更多
Evening l夕情丶
3楼-- · 2020-03-26 04:22

I have made a little script, exactly for this purpose:

https://github.com/mudroljub/js-async-loader

In short, it loads all your scripts asynchronously, and then executes them consequently. It looks something like this:

for (var lib in libs) {
    loadAsync(lib);
}

And you don't need document.write();

查看更多
Juvenile、少年°
4楼-- · 2020-03-26 04:24

Use a script loader (like the one I wrote: LABjs), which will normalize all the different quirks of loading across the various browsers. And bonus: it doesn't use that god-awful document.write(). LABjs will let you load all your scripts asynchronously (in parallel), but make sure they execute in the proper order. Sounds like basically exactly what you want.

查看更多
甜甜的少女心
5楼-- · 2020-03-26 04:34

I guess you could chain the onload event of one to start the load of another:

var newJS= document.createElement('script');
newJS.onload=function() {alert("done")} //or call next load function
newJS.src="..."
document.body.appendChild(newJS)
查看更多
登录 后发表回答