Does script async tag preserve script order of execution?

半世苍凉 提交于 2019-12-11 16:49:09

问题


All concerns of combination, minification, gzipping, and cache aside. Does marking a script as async still preserve script execution order?

Say I have a page where jquery is included at the top followed by other scripts at the bottom that assume the presence of jquery.

If I mark the jquery script with the async attribute I know the browser will continue parsing my html. However, will the browser guarantee that jquery is loaded before my other scripts execute or might things happen out of order resulting in an undefined $?


回答1:


Making a script async does not guarantee any synchronous execution, except that of the script itself.

<script async src="jquery.js"></script>
<script>
    $.noop() // will definitely throw an error
</script>

<script async src="jquery.js"></script>
<script src="someOtherNonAsyncScript.js"></script>
<script>
    $.noop() // may or may not throw an error
</script>



回答2:


No. It will execute asynchronously.

The async and defer attributes are boolean attributes that indicate how the script should be executed. (...)

http://www.whatwg.org/specs/web-apps/current-work/multipage/scripting-1.html#attr-script-async



来源:https://stackoverflow.com/questions/15099370/does-script-async-tag-preserve-script-order-of-execution

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!