Is placing <script>
tags in just before closing the <body>
tag开发者_Python百科 the same sa placing them in the <head>
section and specifying a defer="defer"
attribute?
Yes/No.
Yes because placing the defer tag waits until the document is loaded before executing.
No because placing the <script>
before the </body>
tag doesn't necessarily mean the document is completely loaded as you can have other tags between the closing body tag and the closing HTML tag. Example
<html>
<head>
</head>
<body>
<script>...</script>
</body>
<link/>
<script>
although it is invalid HTML most browsers will render tags outside the body. This is
probably more of an error in code
<div> some content</div>
</html>
Also of note, the defer attribute of the script tag is not functional in all browsers.
Edited:
In regards to performance for faster loading pages you may want to look at this article it provides some guidelines including where to put script and css
http://developer.yahoo.com/performance/rules.html
defer Requires Gecko 1.9.1 This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed. Since this feature hasn't yet been implemented by all other major browsers, authors should not assume that the script’s execution will actually be deferred. Never call document.write() from a defer script (since Gecko 1.9.2, this will blow away the document). The defer attribute shouldn't be used on scripts that don't have the src attribute. Since Gecko 1.9.2, the defer attribute is ignored on scripts that don't have the src attribute. However, in Gecko 1.9.1 even inline scripts are deferred if the defer attribute is set.
When the document has finished parsing and at the end of the <body>
tag are similar but not the exact same.
It's also important to note this only works for scripts with an external src
set.
Generally yes, but the browsers do not guarantee they will execute JavaScript after loading the page unless you specify so (defer="defer").
精彩评论