Should javascript be put in the head or body?

I made a blank blogger page here which removes the automatically added css stylesheet template.
http://test2codes.blogspot.com/

Same as the blank blogger, just on jsfiddle.

I was thinking putting all the javascript at the top of the page above the CSS, but maybe that’s not a good idea.

  <head>
    <b:if cond='data:blog.isMobile'>
      <meta content='width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0' name='viewport'/>
      <b:else/>
      <meta content='width=1100' name='viewport'/>
    </b:if>
    <b:include data='blog' name='all-head-content'/>
    <title>
      <data:blog.pageTitle/>
    </title>

    <b:skin><![CDATA[
    
    ]]></b:skin>
  </head>

Usually the link to the JavaScript file should be put just before the closing body tag, so that the page is fully loaded before the JavaScript tries to run. Although sometimes there might be reasons to keep it up in the head.

This is in answer to the question in your title. I’m not sure what that question has to do with your post, though.

1 Like

I’m referring to the <script> </script> code.

The flow of it currently goes.

CSS

HTML

Javascript

How it is currently set up.

<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<script></script>
<script></script>
<script></script>
<script></script>
<script></script>
<script></script>
<script></script>

You wouldn’t do it like this, right?
@Paul_Wilkins

<div></div>
<script></script>
<div></div>
<script></script>
<div></div>
<script></script>
<div></div>
<script></script>
<div></div>
<script></script>
<div></div>
<script></script>
<div></div>
<script></script>

No. Place all of the JavaScript together in one <script></script> just before the closing body tag. Never spread it out throughout your html. Better still, put it in a separate file and link to that file in script tags that are just before the closing body tag.

2 Likes

ok, I didn’t know I could do that.

I just need one pair of these and not 7 pairs.
<script></script>

Yes. You target each part of the html that you are working with by selecting the appropriate id or class name or element. So the “different scripts” won’t get mixed up with each other.

3 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.