Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - Is it necessary to put scripts at the bottom of a page when using the "defer" attribute?

I always put my script tags at the bottom of the page since it's good practice to load scripts after things like HTML/CSS and text has finished loading. I just found out about the defer attribute which basically does the same thing, that is it waits till the page has finished loading before fetching and executing scripts.

So if using the defer attribute is it necessary to physically place script tags at the bottom of the page vs inside the head tag?

I find it better for readability to keep script tags inside the head section.

<script src="script.js" defer="defer"></script>

or

<script defer="defer">

// do something

</script>
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The current best practice? Use deferred scripts in order in the head, unless you need to support older browsers (IE < 10, Opera Mini, etc.) - 97.45% browser usage (ref)

Why? With defer, parsing finishes just like when we put the script at the end of the body tag, but overall the script execution finishes well before, because the script has been downloaded in parallel with the HTML parsing. This scenario will trigger the faster domInteractive event that is used for page loading speed. With async, the order in which your script will execute varies based on how fast the script is fetched, so order can be compromised. Futhermore, async scripts are executed inline and pause the parsing of the HTML.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...