Where to place JavaScript in an HTML file?

前端 未结 12 2374
萌比男神i
萌比男神i 2020-11-22 04:30

Say I have a fairly hefty JavaScript file, packed down to roughly 100kb or so. By file I mean it’s an external file that would be linked in via

12条回答
  •  爱一瞬间的悲伤
    2020-11-22 05:13

    Putting the javascript at the top would seem neater, but functionally, its better to go after the HTML. That way, your javascript won't run and try to reference HTML elements before they are loaded. This sort of problem often only becomes apparent when you load the page over an actual internet connection, especially a slow one.

    You could also try to dynamically load the javascript by adding a header element from other javascript code, although that only makes sense if you aren't using all of the code all the time.

提交回复
热议问题