Placement of scripts


A question for the more knowledgeable people here.

I am building a very big web project and more and more scripts get involved.

They always say place in between the “head” tags.
Well the head is getting longer and longer.

I have done some research in the net and came to the conclusion that most, if not all, scripts actually can be place in the body (or at the bottom of the body) so they are only executed when called upon.

Most have no need to be executed on the index, maybe just a page here and there.

It seems to me a far better solution then having them all in the head.

Or am I wrong about this?

Thanks for any advice/idea’s, Ron

Well I don’t know what type of scripts you are referring to but usually you can just call to external files that have the scripts in them when needed instead of placing all the code on one page. Yes its possible and the cleaner way to do things. I’m not really a coder so I can’t tell you much more than the possibility (since I’ve made stuff calling to external java script files mostly…)

You are wrong about that. Whether a script is executed or not does not depend on whether it is referred to in the HEAD or BODY element. Maybe you are confusing things? The browser has to fetch the file and interpret the code which takes time. So when and how that is done affects the performance, and thus a decision on whether or not to refer to the code in HEAD or BODY based on what the code is meant to accomplish. Whether or not it is executed depends on logic, whether through code adding another SCRIPT element or the HTML generator including SCRIPT elements selectively.

Best to load scripts asynchronously so they don’t hang-up the page. That said, some scripts need to be in the body because they generate content. Others are best placed in the head because they enable the browser to perform actions. It is these that should be loaded asynchronously.

     var a = document.createElement('script');
     a.type = 'text/javascript';
     a.async = true;
     a.src = '';
     var b = document.getElementsByTagName('script')[0];
     b.parentNode.insertBefore(a, b);

Also, there is an async attribute for the script tag in HTML5 (spec). Example:

<script async src=""></script>

Another version is:

<script src="" async="true">

The documented browser support for both versions is Firefox 3.6+, IE 10+, Chrome 2+, Safari 5+, iOS 5+, Android 3+ (no Opera support yet.) However, I’ve found that support isn’t consistent. YMMV