Where to place JavaScript in an HTML file?

前端 未结 12 2227
萌比男神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:12

    The answer to the question depends. There are 2 scenarios in this situation and you'll need to make a choice based on your appropriate scenario.

    Scenario 1 - Critical script / Must needed script

    In case the script you are using is important to load the website, it is recommended to be placed at the top of your HTML document i.e, . Some examples include - application code, bootstrap, fonts, etc.

    Scenario 2 - Less important / analytics scripts

    There are also scripts used which do not affect the website's view. Such scripts are recommended to be loaded after all the important segments are loaded. And the answer to that will be bottom of the document i.e, bottom of your before the closing tag. Some examples include - Google analytics, hotjar, etc.

    Bonus - async / defer

    You can also tell the browsers that the script loading can be done simultaneously with others and can be loaded based on the browser's choice using a defer / async argument in the script code.

    eg.

提交回复
热议问题