以下代码片段来自Google API文档中的示例。这个代码片段有趣的部分是,在
<head>
中的两个<script async>
的onload
事件处理程序是在后面的<body>
中定义的。异步脚本中的onload
事件只有在解析完<body>
后才会触发吗?是否有任何规范提供了这样的保证?或者这段代码仅在暗示这两个特定的<head>
脚本需要很长时间来获取和执行的前提下才正确?<!DOCTYPE html>
<html>
<head>
<script async defer src="https://apis.google.com/js/api.js" onload="gapiLoad()"></script>
<script async defer src="https://accounts.google.com/gsi/client" onload="gisInit()"></script>
</head>
<body>
<script>
function gapiLoad() {
// do something
}
function gisInit() {
// do something
}
// there are other stuffs...
</script>
</body>
</html>