Search code examples
javascriptdeferredhead

JavaScript defering


Is placing <script> tags in just before closing the <body> tag the same sa placing them in the <head> section and specifying a defer="defer" attribute?


Solution

  • 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