Is order of script onload and [removed] well defin

2019-04-28 09:21发布

File loader.js:

function main()
{
  if (typeof window !== 'undefined') {
    var script = window.document.createElement('script')
    script.src = 'https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.core.min.js'
    script.onload = function () { console.log('script loaded') }
    window.onload = function () { console.log('window loaded') }
    window.document.head.appendChild(script)
  } else {
    console.log('window not available yet')
  }
}

if (typeof module !== 'undefined' && module.exports) {
  exports.main = main
}

main()

File window.html:

<!DOCTYPE html>
<html>
  <head>
    <title>Test</title>
    <script src="loader.js"></script>
  </head>
  <body>
    <div>Test</div>
  </body>
</html>

Console output when I open this HTML page:

script loaded
window loaded

My question:

In the above code, is it guaranteed that the script onload event always fires before the window onload?

1条回答
Ridiculous、
2楼-- · 2019-04-28 10:04

Yes, the output you see is guaranteed, because the load event is fired "when a resource and its dependent resources have finished loading." The window will not be fully loaded until every element with something to download is downloaded and ready, including scripts and images. So, the <script> has to load before the window loads.

The fact that there's a script which is created dynamically won't have an effect (assuming that main is called before the window is fully loaded, like in your code) - once inserted into the DOM, it's now something the window depends on, and so must load before the window does.

查看更多
登录 后发表回答