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

后端 未结 9 1212
渐次进展
渐次进展 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:48

    When the browser encounters a script element it has to evalute the JavaScript contained in that element because the script might alter the content of the page (via document.write) or inspect the current state of the page.

    If the script element loads script using the src attribute, loading of other resources (JavaScript, CSS, images, etc.) will be blocked until the current script is loaded.

    Both of these factors can slow down the perceived load time of your page.

    If your JavaScript does not alter the page or if it doesn't need to inspect the state of the page until it has loaded you can mark your script element with defer="defer" (supported by IE 6+ and Firefox 3.5+) which indicates that the evaluation of the script can happen "later". Moving your script elements to the bottom of the page effectively does the same thing - since your scripts appear at the end of the document they'll be evaluated after CSS, images, etc. are loaded and the HTML is rendered.

提交回复
热议问题