Why do some developers put a script tag at the bottom of the document?

Possible duplicate:
Can I put JS files at the bottom of a web page?

I saw HTML documents where developers put <script src="xxx"> tags at the bottom of the document and wonder why.

I just read the HTML4 spec regarding script tag . It does not say anything about when and how to load the script. Therefore, it is up to the web browser to handle this on its own.

Is it not reasonable to think that the authors of the browser should know that loading scripts synchronously or in any other way impedes the rendering of the document and affects the viewing?

i.e. aren't we, as web developers, better putting scripts in the <head> ?

+4
source share
4 answers

Scenarios require interpretation (which can be relatively expensive) and may optionally request a request through another HTTP request. Placing them at the end of the document allows you to load the rest of the page.

Scripts without the async or defer attributes are retrieved and executed immediately before the browser continues to parse the page.

https://developer.mozilla.org/en-US/docs/HTML/Element/script

See also http://dev.w3.org/html5/spec/the-script-element.html , namely the areas around preparation / blocking, which are described in detail. Note that this is an editorial project in a stream; some of these rules may not be in the final specification or applied by all user agents.

As a side note, this locking behavior is not bad / wrong. Think of a library like Modernizr , which refers to head . It modifies the DOM in a way that allows CSS to be applied correctly; if they were executed in parallel, the results would be incorrect.

+3
source

Placing script tags at the top of the document can block the rest of the page from loading; this is especially true in banner advertising scenarios. If a third-party script device takes a long time to load, any DOM element is then delayed, resulting in a blank / invalid page until the request expires or the content eventually loads.

+3
source

Thus, the document will be fully displayed until the JavaScript code is launched. If the script takes time or does not work or is unavailable, it will not leave the user sitting in front of a blank page.

In addition, when performing DOM manipulations to the full body element, an IE error may occur.

0
source
  • The JS script is executed at the point where this happens when the page loads. If it is at the top of the page, the rest of the page will not be loaded when it starts, which means that it will not be able to access any elements on the page.

  • If the script takes time to run (say, it has a slow cycle or generates an alert() window or does something else that blocks execution), then the rest of the page load will be delayed until it finishes. If the script is in <head> , this can lead to the user seeing a blank page, and the script will do so.

0
source

Source: https://habr.com/ru/post/1438401/


All Articles