When do you choose to load your javascript at the bottom of the page instead of the top?

后端 未结 9 1216
渐次进展
渐次进展 2020-12-10 17:15

I have seen JavaScript libraries being loaded at the top and bottom of the page.

I would love to know when to make these choices. All the JavaScript code I\'ve writt

9条回答
  •  生来不讨喜
    2020-12-10 17:57

    Simply put, if your script have snippets that would start executing right away (outside all function(){} bodies) and that access DOM elements, it should go at the end of the page so that DOM would have been built and be ready to be accessed by the time the script starts executing.

    If you are accessing DOM only from function calls (like onload, onclick etc), you can put the script safely in the head section itself.

提交回复
热议问题