Jump to content

Where to place script tags.


Braxton

Recommended Posts

Sometimes I read that folks include the script tag(with javascript files) between head tags and other times I read about folks placing the script tags directly before the closing body tag. Which is the more sufficient way to do this? Does it really even matter?

Link to comment
Share on other sites

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.

 

 

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

  • 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/

Link to comment
Share on other sites

  • 4 weeks later...
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.