AdamNYC
AdamNYC

Reputation: 20415

Where should I include javascript on a page?

I am building a Rails app, and it seems that common practice is to have javascript_include_tags listed on top of a page.

Would it makes browers load javascript before loading the document, and thus makes visible elements take longer to load?

Thank you.

Upvotes: 1

Views: 172

Answers (5)

Florian Margaine
Florian Margaine

Reputation: 60717

Looks like some answers were right, but none sums it all up:

  • How to prevent javascript loading from loading other elements? Simple, put it right before the closing </body> tag. Which usually means a few characters before the end of your HTML page.
  • Put all your javascript in external .js files. Why? So that the browsers can cache those files even when the HTML page changes.
  • Aggregate and minify all your javascript files into one. Why? Because the fewer HTTP requests your clients make, the faster the page loads.

Also, you don't have to care about $(document).ready() or window.onload, since all your HTML elements will be loaded before the javascript files (that is, if you put the JS files right before the closing </body> tag).

Upvotes: 3

edlizano
edlizano

Reputation: 15

Rather than embedding the behavior in its markup, try to segregate the script by moving it to a script block in the section of the page, outside the scope of the document body, as follows:

<script type="text/javascript">
window.onload = function() {
document.getElementById('testButton').onclick = function() {
document.getElementById('xyz').style.color = 'red';
};
};
</script>

For performance reasons, script blocks can also be placed at the bottom of the document body, though modern browsers make the performance difference rather moot. The important concept is to avoid embedding behavioral elements within the structural elements.

Upvotes: 0

ZZ-bb
ZZ-bb

Reputation: 2167

It's a good idea to use external JS file and to minify it's content.

Bottom of the page is also an option like John Fisher said.

If using i.e. jQuery you in any case use $() or $(document).ready(function() which makes sure the page DOM is loaded before you try to use your JS functions.

Upvotes: 0

Armatus
Armatus

Reputation: 2191

A Yahoo post about web page performance suggests including them at the bottom of the page (Source) because they can block parallel downloads of other dependencies if they are at the top.

Upvotes: 4

John Fisher
John Fisher

Reputation: 22719

As far as I've read on the web, best practice loads javascript files at the bottom of the body tag. This lets almost everything load before executing the javascript, which generally prevents problems accessing items that may not exist if you loaded the script at the top.

Upvotes: 5

Related Questions