Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do you choose to load your javascript at the bottom of the page instead of the top?

I have seen JavaScript libraries being loaded at the top and bottom of the page.

I would love to know when to make these choices. All the JavaScript code I've written all work at the top of the page, which includes jquery plugins.

When do i load my script at any of these positions?

like image 646
Orson Avatar asked Dec 07 '09 14:12

Orson


4 Answers

Top: When having JavaScript events function on elements immediately is more important (so if you use a DOM Ready event to load everything, this is the wrong place)

Bottom: When loading the content is more important

like image 80
Quentin Avatar answered Oct 01 '22 16:10

Quentin


Yahoo says to Put Scripts at the Bottom. Google says something similar but not as clearly.

like image 38
nickf Avatar answered Oct 01 '22 16:10

nickf


The reason you do it at the bottom of the page is because if you put it at the top of your page then the rendering of your page will wait for these files before it renders. This is why a lot of people put JavaScript at the bottom of the page as it allows the entire page to be rendered then the JavaScript is loaded.

There's very rarely any reason you'd want to put the JavaScript at the top of the page, and unless you have an explicit reason you want the JavaScript loaded in before the main page then put it at the bottom. Most optimization guides suggest putting it at the bottom for this reason.

like image 21
fyjham Avatar answered Oct 01 '22 15:10

fyjham


I place all CSS in the HEAD to avoid excessive screen paintings and flashes of style.

I place most JavaScript file requests at the bottom of the page so that the page can render quickly (HTML/CSS loading will block until script tags above them have been loaded and processed). Any code that needs to be executed after the library files have loaded are executed onDOMReady, which is all code except for library initialization. I pretty much followed Google's PageSpeed recommendations.

I've been thinking about using LABjs as well to further decrease page load times, but this works well enough right now.

like image 31
James van Dyke Avatar answered Oct 01 '22 15:10

James van Dyke