Why put JavaScript in head

后端 未结 8 1891
被撕碎了的回忆
被撕碎了的回忆 2020-12-24 11:18

If it is perfectly acceptable to put JavaScript right before what is a good reason to keep it in the ?

Based on t

8条回答
  •  独厮守ぢ
    2020-12-24 11:37

    In the past, the only reason to put JS in the head was for scripts that modify how the browser actually renders the page (as Chris Pratt pointed out). Today, that's no longer the case, though :

    • If you still care a lot about support and performance in IE<10, it remains the best approach to make your script tags the last tags of your HTML body. That way, you're certain that the rest of the DOM has been loaded and you won't block and rendering.

    • If you don't care too much anymore about IE<10, you might want to put your scripts in the head of your document and use defer to ensure they only run after your DOM has been loaded (). The beauty of this approach, is that defer doesn't block loading the rest of the DOM. If you still want your code to work in IE<10, don't forget to wrap your code in a window.onload even, though!

提交回复
热议问题