问题
So, I'm following the Google PageSpeed recommendation to defer above-the-fold scripts. Let's say this is the code in my <head>
:
<script src="/js/jquery.js"></script>
<script src="/js/functions.js"></script>
The functions.js
script depends on jQuery so it's crucial that jquery.js
is loaded and executed before functions.js
.
What I tried:
defer
<script src="/js/jquery.js" defer></script>
<script src="/js/functions.js" defer></script>
While this works and functions.js
gets executed properly, when I load the page I see it flicker, as if the CSS is not yet loaded. Note that the above code is in the <head>
. If I remove the defer
attribute from jquery.js
, the flickering disappears. That leads me to my question:
Mixed
<script src="/js/jquery.js" async></script>
<script src="/js/functions.js" defer></script>
Does using async
on the dependency script and defer
on the dependent script ensure they will always be executed in that order? It seems to work in my tests but I don't know enough about how the parser works in order to be sure.
回答1:
The answer is that you lose guarantees about the order scripts are executed if you use async
or defer
.
async
scripts are executed asyncronously, there are no guarantees as to which order there are. defer
scripts are executed after the document has been parsed, but there are no guarantees as to whether they will be executed in order. (Have a look at this question about defer scripts specifically.)
Unfortunately, in your case, you have to run jquery.js
synchronously by removing the defer
and async
attributes.
Looking forward, as we move to modules, specifying dependencies and loading them just in time (and only once) will be made much easier.
回答2:
Although I'm not sure how current browsers implement the standard, there are minimal guarantees about execution order of scripts (classic script elements without type="module") and modules (script elements with type=module).
1) Classic scripts which do not specify defer or async are executed in the order they appear in the html document (when the document is being parsed). They are executed before classic scripts that are defer and modules that are not async.
2) classic scripts that are defer and modules that are not async are executed in the order they appear in the html document (after the document has been parsed).
See point 20 on the processing model here: https://www.w3.org/TR/html5/semantics-scripting.html#script-processing-model
回答3:
Yes on chrome, sometimes on Firefox..
Specs say they will be loaded in order, but loaded mean downloaded not executed so if file finishes downloading before other it will run first so i wouldn't recommend you depend on order of execution using defer or async attributes
来源:https://stackoverflow.com/questions/46978612/using-async-and-defer-to-load-scripts-in-order