javascript - Javascript 内联脚本和延迟脚本的执行顺序
问题描述
我对混合脚本类型的执行顺序有疑问。
这是我的代码:
<script>
if(document.documentMode) {
const firstScriptInDOM = document.getElementsByTagName('script')[0];
const polyfill = document.createElement('script');
polyfill.src = "/static/js/polyfills/polyfills.js";
firstScriptInDOM.parentNode.insertBefore(polyfill, firstScriptInDOM);
}
</script>
<script src="static/js/lib1.js" defer></script>
<script src="static/js/lib2.js" defer></script>
<script src="static/js/lib3.js" defer></script>
<script src="static/js/myOwnScriptFile.js" defer></script>
如果浏览器是 IE,第一个脚本标签的目的是为 IE 加载 polyfills。然后它应该加载其他脚本并执行我的代码。
我的问题是:polyfills 脚本会阻止延迟脚本的执行吗?
非常感谢您的时间!
解决方案
脚本同步加载,除非指定使用async
属性异步加载,该defer
属性的作用是仅在加载 DOM 后加载脚本。如果您动态附加脚本,它将异步加载。
在你的情况下,
这应该是执行链:
- 检查 polyfill 脚本执行
- 库1
- 库2
- 库3
- 我的脚本文件
- polyfills(仅在解析器完成执行后下载)
为了确保所有脚本都按照您想要的顺序加载,您可以使用以下内容动态加载所有脚本:
检查浏览器是否为IE:
IF IE
load polyfills, and load other scripts in the onload event of the polyfills script.
ELSE
load all other scripts
推荐阅读
- c# - 在同一个地方打印数字
- .net-core - .NET Core 运行状况检查:找不到所需的服务
- vba - 基于另一列值的 VBA Subtotal(9,"range")
- c# - 如何从 Web API 调用 ASP.NET Core Web MVC
- c# - 2sxc 获取实体的字段列表
- python - 装饰器的类型注释
- asp.net-core - 无法通过 Envoy (v1.17.0) 将 API 调用转发到 docker-compose (v1.27.4) 内的各自路由
- flutter - 未布置 RenderBox - 具有动态子项的特殊情况
- discord - discord.js \n 转义字符在使用 setDescription 的嵌入中不起作用
- php - 在 R 中使用 fromJSON 从 url 读取 json 输出,同时从文本文件中读取相同数据时出现“未定义的索引错误”