2
votes

I was wondering what situations force you to include javascript in the head section and not before the body ends?

I mean what do the scripts that are required to be in the head usually do?

6

6 Answers

3
votes

For example they could fire off AJAX requests to fetch JSON data from the server while the rest of the document continues to load.

2
votes

Only document.write() and dependencies between scripts put a requirement on scripts position in the page.

If a script provides methods that can be used anywhere in the <body>, it is convenient to put the script in <head>, and I believe this is why scripts are often placed in <head>.

But I can't think of any reason which would require a script to be placed in <head>.

2
votes

See the very last paragraph on Quirksmode.org http://www.quirksmode.org/js/placejs.html

Your question is a little broad, so this answer is rather broad as well.

1
votes

If you want to fire JavaScript code before page load event, the only condition which I thinks.

1
votes

HTML is a liberal document language, which is why it's so popular. You are not required to place your scripts anywhere in particular.

I mean what do the scripts that are required to be in the head usually do?

Usually you include your libraries/extensions first and foremost in the document. Larger sites don't bother with static HTML pages, instead opting for Content Management Systems. CMSs tend to be highly modular. Allowing the placement of various different content types within various regions of the page. To maintain modularity a simple inline script may be used (especially when using jQuery):

<input id="super-special-date-field" type="text" name="ssdf" />
<script type="text/javascript">$('#super-special-date-field').datepicker();</script>

This works great assuming jQuery is included in the page, but if it's included at the bottom, this simple script will throw an error.

You could make your scripts wait for document.ready or window.onload, but it's easier not to.

Any non-essential scripts can then be placed at the bottom of the page. IMHO if your loading time is under 1s, most people wont be bothered by the load time.

1
votes

The most important thing I usually put in the <head> is a basic early event handling. So that I catch every event from the very start and execute them when the DOM and proper event handlers are fully loaded.

to the <head>

var earlyEvents = { ... };

// catch every user event, even
// before the DOM is fully loaded
document.onclick = function(event) {
  earlyEvents.register("click", event);
};

DOMContentLoaded handler

// execute them when the page is ready
earlyEvents.executeAll();

It's important that jQuery may not be available in the <head> so earlyEvents has to save/copy the event objects, because they're only active during the first execution. You may use a simple loop and trigger in executeAll.

Facebook does something similar with Primer