Is there a known workaround for IE9's execution order of injected script tags?

試著忘記壹切 提交于 2019-12-30 11:06:07

问题


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.


回答1:


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.




回答2:


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)



回答3:


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.




回答4:


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();



来源:https://stackoverflow.com/questions/7126270/is-there-a-known-workaround-for-ie9s-execution-order-of-injected-script-tags

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!