Jump to content

Where to place script tags.


Braxton

Recommended Posts

The nicest way to include JS to your HTML is with a separate .js file linked with the src attribute of the script tag in the head section of the site. Otherwise if you mix both JS and HTML your code will get messy and the pageload time will increase significatnly.

 

 

If the script does not need to modify the document during the load process (which most don't) then it is generally recommended to put the script before the </body> tag.  Doing so allows the browser to get the HTML document rendered to the screen before it spends time loading the scripts for the page.

 

Generally though it doesn't really matter where you put them.

  • 3 weeks later...

Kicken is correct.

 

Each script requires a separate HTTP request. Browser limitations mean that only two concurrent requests can be made to each domain. If you have a bunch of images and scripts on your page, and you put your scripts in the head, other elements have to wait for scripts to download before they can be downloaded, slowing down the pageload for the main content. On top of this, scripts are immediately executed upon download (which is why you generally need onload functions in JS), which takes resources, and slows the page load down even more.

 

By putting scripts that don't contain functionality required during page load at the end of the page, it ensures that all other content is loaded first, for a better user experience.

 

This isn't even a new debate - this has been accepted as a best practice for years. Look at the section "put scripts at the bottom" on this page: http://developer.yahoo.com/performance/rules.html/

  • 4 weeks later...

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.