Reputation: 20415
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
Reputation: 60717
Looks like some answers were right, but none sums it all up:
</body>
tag. Which usually means a few characters before the end of your HTML page.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
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
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
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
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