JavaScript 的 document.write 内联脚本执行顺序 [英] JavaScript's document.write Inline Script Execution Order

查看:29
本文介绍了JavaScript 的 document.write 内联脚本执行顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下脚本,其中第一个和第三个 document.writeline 是静态的,第二个是生成的:

I have the following script, where the first and third document.writeline are static and the second is generated:

<script language="javascript" type="text/javascript">
document.write("<script language='javascript' type='text/javascript' src='before.js'></sc" + "ript>");
document.write("<script language='javascript' type='text/javascript'>alert('during');</sc" + "ript>");
document.write("<script language='javascript' type='text/javascript' src='after.js'></sc" + "ript>");
</script>

Firefox 和 Chrome 将显示 beforeduringafter,而 Internet Explorer 首先显示 during 并且仅然后它会显示beforeafter.

Firefox and Chrome will display before, during and after, while Internet Explorer first shows during and only then does it show before and after.

我看到一篇文章说我不是第一个遇到这种情况,但这几乎让我感觉好些.

I've come across an article that states that I'm not the first to encounter this, but that hardly makes me feel any better.

有谁知道我如何在所有浏览器中将顺序设置为确定性的,或者如何破解 IE 使其像所有其他正常浏览器一样工作?

注意事项:代码片段是一个非常简单的重现.它是在服务器上生成的,第二个脚本是唯一改变的东西.这是一个很长的脚本,并且前后有两个脚本的原因是浏览器会缓存它们并且代码的动态部分会尽可能小.它也可能在同一个页面中使用不同的生成代码多次出现.

Caveats: The code snippet is a very simple repro. It is generated on the server and the second script is the only thing that changes. It's a long script and the reason there are two scripts before and after it are so that the browser will cache them and the dynamic part of the code will be as small as possible. It may also appears many times in the same page with different generated code.

推荐答案

我找到了更合我意的答案:

I've found an answer more to my liking:

<script language="javascript" type="text/javascript">
document.write("<script language='javascript' type='text/javascript' src='before.js'></sc" + "ript>");
document.write("<script defer language='javascript' type='text/javascript'>alert('during');</sc" + "ript>");
document.write("<script defer language='javascript' type='text/javascript' src='after.js'></sc" + "ript>");
</script>

这将延迟 duringafter 的加载,直到页面完成加载.

This will defer the loading of both during and after until the page has finished loading.

我认为这是我能得到的最好的.希望有人能够给出更好的答案.

I think this is as good as I can get. Hopefully, someone will be able to give a better answer.

这篇关于JavaScript 的 document.write 内联脚本执行顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆