Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
616 views
in Technique[技术] by (71.8m points)

javascript - Using async and defer to load scripts in order

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...