我有3个脚本需要按顺序执行,每个下一个脚本等待上一个脚本完成执行。有没有更快更优雅的方式来写这篇文章?
例如,我有一个生产html页面,需要按顺序加载20个脚本。
注意:向每个脚本添加defer不会按顺序执行脚本。
以下是一个工作示例:
index.html
<html>
<head>
<title>Load scripts in order</title>
<script>
const scripts = ["script1.js", "script2.js", "script3.js"]
for (let i = 1; i < scripts.length; i++) {
document.head.addEventListener(scripts[i - 1], () => {
console.log(`finished processing ${scripts[i - 1]}`)
const nextScript = document.createElement("script")
nextScript.src = scripts[i]
document.head.appendChild(nextScript)
})
}
</script>
<!--load our first script to start sequential loading-->
<script src="script1.js"></script>
</head>
<body>
<h1>Hello world</h1>
</body>
</html>
script1.js
const foobar = async () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve()
}, 3000)
setTimeout(() => {
reject(new Error("did not finish in time."))
}, 10000);
})
}
foobar().then(() => {
console.log("finished loading script1.js")
document.head.dispatchEvent(new Event("script1.js"))
} )
script2.js
const foobar2 = async () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve()
}, 3000)
setTimeout(() => {
reject(new Error("did not finish in time."))
}, 10000);
})
}
foobar2().then(() => {
console.log("finished loading script2.js")
document.head.dispatchEvent(new Event("script2.js"))
} )
script3.js
console.log("hello world")
堆栈跟踪:
finished loading script1.js
finished processing script1.js
finished loading script2.js
finished processing script2.js
hello world