[javascript] Where to place JavaScript in an HTML file?

Say I have a fairly hefty JavaScript file, packed down to roughly 100kb or so. By file I mean it’s an external file that would be linked in via <script src="...">, not pasted into the HTML itself.

Where’s the best place to put this in the HTML?

<html>
<head>
    <!-- here? -->
    <link rel="stylesheet" href="stylez.css" type="text/css" />
    <!-- here? -->
</head>
<body>
    <!-- here? -->
    <p>All the page content ...</p>
    <!-- or here? -->
</body>
</html>

Will there be any functional difference between each of the options?

This question is related to javascript html optimization

The answer is


With 100k of Javascript, you should never put it inside the file. Use an external script Javascript file. There's no chance in hell you'll only ever use this amount of code in only one HTML page. Likely you're asking where you should load the Javascript file, for this you've received satisfactory answers already.

But I'd like to point out that commonly, modern browsers accept gzipped Javascript files! Just gzip the x.js file to x.js.gz, and point to that in the src attribute. It doesn't work on the local filesystem, you need a webserver for it to work. But the savings in transferred bytes can be enormous.

I've successfully tested it in Firefox 3, MSIE 7, Opera 9, and Google Chrome. It apparently doesn't work this way in Safari 3.

For more info, see this blog post, and another very ancient page that nevertheless is useful because it points out that the webserver can detect whether a browser can accept gzipped Javascript, or not. If your server side can dynamically choose to send the gzipped or the plain text, you can make the page usable in all web browsers.


The answer is depends how you are using the objects of javascript. As already pointed loading the javascript files at footer rather than header certainly improves the performance but care should be taken that the objects which are used are initialized later than they are loaded at footer. One more way is load the 'js' files placed in folder which will be available to all the files.


The best place for it is just before you need it and no sooner.

Also, depending on your users' physical location, using a service like Amazon's S3 service may help users download it from a server physically closer to them than your server.

Is your js script a commonly used lib like jQuery or prototype? If so, there are a number of companies, like Google and Yahoo, that have tools to provide these files for you on a distributed network.


Using cuzillion you can test the affect on page load of different placement of script tags using different methods: inline, external, "HTML tags", "document.write", "JS DOM element", "iframe", and "XHR eval". See the help for an explanation of the differences. It can also test stylesheets, images and iframes.


Putting the javascript at the top would seem neater, but functionally, its better to go after the HTML. That way, your javascript won't run and try to reference HTML elements before they are loaded. This sort of problem often only becomes apparent when you load the page over an actual internet connection, especially a slow one.

You could also try to dynamically load the javascript by adding a header element from other javascript code, although that only makes sense if you aren't using all of the code all the time.


Using cuzillion you can test the affect on page load of different placement of script tags using different methods: inline, external, "HTML tags", "document.write", "JS DOM element", "iframe", and "XHR eval". See the help for an explanation of the differences. It can also test stylesheets, images and iframes.


The best place for it is just before you need it and no sooner.

Also, depending on your users' physical location, using a service like Amazon's S3 service may help users download it from a server physically closer to them than your server.

Is your js script a commonly used lib like jQuery or prototype? If so, there are a number of companies, like Google and Yahoo, that have tools to provide these files for you on a distributed network.


The scripts should be included at the end of the body tag because this way the HTML will be parsed by the browser and displayed before the scripts are loaded.


I would say that it depends of fact what do you planed to achieve with Javascript code:

  • if you planned to insert external your JS script(s), then the best place is in head of the page
  • if you planed to use pages on smartphones, then bottom of page, just before tag.
  • but, if you planned to make combination HTML and JS (dynamically created and populated HTML table, for example) then you must put it where you need it there.

The best place for it is just before you need it and no sooner.

Also, depending on your users' physical location, using a service like Amazon's S3 service may help users download it from a server physically closer to them than your server.

Is your js script a commonly used lib like jQuery or prototype? If so, there are a number of companies, like Google and Yahoo, that have tools to provide these files for you on a distributed network.


Putting the javascript at the top would seem neater, but functionally, its better to go after the HTML. That way, your javascript won't run and try to reference HTML elements before they are loaded. This sort of problem often only becomes apparent when you load the page over an actual internet connection, especially a slow one.

You could also try to dynamically load the javascript by adding a header element from other javascript code, although that only makes sense if you aren't using all of the code all the time.


As a rule of thumb, the best place to put <script> tags is the bottom of the page, just before </body> tag. Something like this:

<html>
    <head>
        <title>My awesome page</title>

        <!-- CSS -->
        <link rel="stylesheet" type="text/css" href="...">
        <link rel="stylesheet" type="text/css" href="...">
        <link rel="stylesheet" type="text/css" href="...">
        <link rel="stylesheet" type="text/css" href="...">

    </head>
    <body>
        <!-- Content content content -->

        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script type="text/javascript" src="..."></script>
        <script type="text/javascript" src="..."></script>
        <script type="text/javascript" src="..."></script>
    </body>
</html>

Why?

The problem caused by scripts is that they block parallel downloads. The HTTP/1.1 specification suggests that browsers download no more than two components in parallel per hostname. If you serve your images from multiple hostnames, you can get more than two downloads to occur in parallel. While a script is downloading, however, the browser won't start any other downloads, even on different hostnames. More...

CSS

A little bit off-topic, but... Put stylesheets at the top.

While researching performance at Yahoo!, we discovered that moving stylesheets to the document HEAD makes pages appear to be loading faster. This is because putting stylesheets in the HEAD allows the page to render progressively. More...

Further reading

Yahoo have released a really cool guide that lists best practices to speed up a website. Definitely worth reading: https://developer.yahoo.com/performance/rules.html


Like others have said, it should most likely go in an external file. I prefer to include such files at the end of the <head />. This method is more human friendly than machine friendly, but that way I always know where the JS is. It is just not as readable to include script files anywhere else (imho).

I you really need to squeeze out every last ms then you probably should do what Yahoo says.


With 100k of Javascript, you should never put it inside the file. Use an external script Javascript file. There's no chance in hell you'll only ever use this amount of code in only one HTML page. Likely you're asking where you should load the Javascript file, for this you've received satisfactory answers already.

But I'd like to point out that commonly, modern browsers accept gzipped Javascript files! Just gzip the x.js file to x.js.gz, and point to that in the src attribute. It doesn't work on the local filesystem, you need a webserver for it to work. But the savings in transferred bytes can be enormous.

I've successfully tested it in Firefox 3, MSIE 7, Opera 9, and Google Chrome. It apparently doesn't work this way in Safari 3.

For more info, see this blog post, and another very ancient page that nevertheless is useful because it points out that the webserver can detect whether a browser can accept gzipped Javascript, or not. If your server side can dynamically choose to send the gzipped or the plain text, you can make the page usable in all web browsers.


The scripts should be included at the end of the body tag because this way the HTML will be parsed by the browser and displayed before the scripts are loaded.


The best place for it is just before you need it and no sooner.

Also, depending on your users' physical location, using a service like Amazon's S3 service may help users download it from a server physically closer to them than your server.

Is your js script a commonly used lib like jQuery or prototype? If so, there are a number of companies, like Google and Yahoo, that have tools to provide these files for you on a distributed network.


Like others have said, it should most likely go in an external file. I prefer to include such files at the end of the <head />. This method is more human friendly than machine friendly, but that way I always know where the JS is. It is just not as readable to include script files anywhere else (imho).

I you really need to squeeze out every last ms then you probably should do what Yahoo says.


The answer to the question depends. There are 2 scenarios in this situation and you'll need to make a choice based on your appropriate scenario.

Scenario 1 - Critical script / Must needed script

In case the script you are using is important to load the website, it is recommended to be placed at the top of your HTML document i.e, <head>. Some examples include - application code, bootstrap, fonts, etc.

Scenario 2 - Less important / analytics scripts

There are also scripts used which do not affect the website's view. Such scripts are recommended to be loaded after all the important segments are loaded. And the answer to that will be bottom of the document i.e, bottom of your <body> before the closing tag. Some examples include - Google analytics, hotjar, etc.

Bonus - async / defer

You can also tell the browsers that the script loading can be done simultaneously with others and can be loaded based on the browser's choice using a defer / async argument in the script code.

eg. <script async src="script.js"></script>


I would say that it depends of fact what do you planed to achieve with Javascript code:

  • if you planned to insert external your JS script(s), then the best place is in head of the page
  • if you planed to use pages on smartphones, then bottom of page, just before tag.
  • but, if you planned to make combination HTML and JS (dynamically created and populated HTML table, for example) then you must put it where you need it there.

The answer is depends how you are using the objects of javascript. As already pointed loading the javascript files at footer rather than header certainly improves the performance but care should be taken that the objects which are used are initialized later than they are loaded at footer. One more way is load the 'js' files placed in folder which will be available to all the files.


The answer is depends how you are using the objects of javascript. As already pointed loading the javascript files at footer rather than header certainly improves the performance but care should be taken that the objects which are used are initialized later than they are loaded at footer. One more way is load the 'js' files placed in folder which will be available to all the files.


As a rule of thumb, the best place to put <script> tags is the bottom of the page, just before </body> tag. Something like this:

<html>
    <head>
        <title>My awesome page</title>

        <!-- CSS -->
        <link rel="stylesheet" type="text/css" href="...">
        <link rel="stylesheet" type="text/css" href="...">
        <link rel="stylesheet" type="text/css" href="...">
        <link rel="stylesheet" type="text/css" href="...">

    </head>
    <body>
        <!-- Content content content -->

        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script type="text/javascript" src="..."></script>
        <script type="text/javascript" src="..."></script>
        <script type="text/javascript" src="..."></script>
    </body>
</html>

Why?

The problem caused by scripts is that they block parallel downloads. The HTTP/1.1 specification suggests that browsers download no more than two components in parallel per hostname. If you serve your images from multiple hostnames, you can get more than two downloads to occur in parallel. While a script is downloading, however, the browser won't start any other downloads, even on different hostnames. More...

CSS

A little bit off-topic, but... Put stylesheets at the top.

While researching performance at Yahoo!, we discovered that moving stylesheets to the document HEAD makes pages appear to be loading faster. This is because putting stylesheets in the HEAD allows the page to render progressively. More...

Further reading

Yahoo have released a really cool guide that lists best practices to speed up a website. Definitely worth reading: https://developer.yahoo.com/performance/rules.html


The answer is depends how you are using the objects of javascript. As already pointed loading the javascript files at footer rather than header certainly improves the performance but care should be taken that the objects which are used are initialized later than they are loaded at footer. One more way is load the 'js' files placed in folder which will be available to all the files.


Your javascript links can got either in the head or at the end of the body tag, it is true that performance improves by putting the link at the end of your body tag, but unless performance is an issue, placing them in the head is nicer for people to read and you know where the links are located and can reference them easier.


Putting the javascript at the top would seem neater, but functionally, its better to go after the HTML. That way, your javascript won't run and try to reference HTML elements before they are loaded. This sort of problem often only becomes apparent when you load the page over an actual internet connection, especially a slow one.

You could also try to dynamically load the javascript by adding a header element from other javascript code, although that only makes sense if you aren't using all of the code all the time.


Using cuzillion you can test the affect on page load of different placement of script tags using different methods: inline, external, "HTML tags", "document.write", "JS DOM element", "iframe", and "XHR eval". See the help for an explanation of the differences. It can also test stylesheets, images and iframes.


Your javascript links can got either in the head or at the end of the body tag, it is true that performance improves by putting the link at the end of your body tag, but unless performance is an issue, placing them in the head is nicer for people to read and you know where the links are located and can reference them easier.


Putting the javascript at the top would seem neater, but functionally, its better to go after the HTML. That way, your javascript won't run and try to reference HTML elements before they are loaded. This sort of problem often only becomes apparent when you load the page over an actual internet connection, especially a slow one.

You could also try to dynamically load the javascript by adding a header element from other javascript code, although that only makes sense if you aren't using all of the code all the time.


With 100k of Javascript, you should never put it inside the file. Use an external script Javascript file. There's no chance in hell you'll only ever use this amount of code in only one HTML page. Likely you're asking where you should load the Javascript file, for this you've received satisfactory answers already.

But I'd like to point out that commonly, modern browsers accept gzipped Javascript files! Just gzip the x.js file to x.js.gz, and point to that in the src attribute. It doesn't work on the local filesystem, you need a webserver for it to work. But the savings in transferred bytes can be enormous.

I've successfully tested it in Firefox 3, MSIE 7, Opera 9, and Google Chrome. It apparently doesn't work this way in Safari 3.

For more info, see this blog post, and another very ancient page that nevertheless is useful because it points out that the webserver can detect whether a browser can accept gzipped Javascript, or not. If your server side can dynamically choose to send the gzipped or the plain text, you can make the page usable in all web browsers.


The answer to the question depends. There are 2 scenarios in this situation and you'll need to make a choice based on your appropriate scenario.

Scenario 1 - Critical script / Must needed script

In case the script you are using is important to load the website, it is recommended to be placed at the top of your HTML document i.e, <head>. Some examples include - application code, bootstrap, fonts, etc.

Scenario 2 - Less important / analytics scripts

There are also scripts used which do not affect the website's view. Such scripts are recommended to be loaded after all the important segments are loaded. And the answer to that will be bottom of the document i.e, bottom of your <body> before the closing tag. Some examples include - Google analytics, hotjar, etc.

Bonus - async / defer

You can also tell the browsers that the script loading can be done simultaneously with others and can be loaded based on the browser's choice using a defer / async argument in the script code.

eg. <script async src="script.js"></script>


Using cuzillion you can test the affect on page load of different placement of script tags using different methods: inline, external, "HTML tags", "document.write", "JS DOM element", "iframe", and "XHR eval". See the help for an explanation of the differences. It can also test stylesheets, images and iframes.


Like others have said, it should most likely go in an external file. I prefer to include such files at the end of the <head />. This method is more human friendly than machine friendly, but that way I always know where the JS is. It is just not as readable to include script files anywhere else (imho).

I you really need to squeeze out every last ms then you probably should do what Yahoo says.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to optimization

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly? Measuring execution time of a function in C++ GROUP BY having MAX date How to efficiently remove duplicates from an array without using Set Storing JSON in database vs. having a new column for each key Read file As String How to write a large buffer into a binary file in C++, fast? Is optimisation level -O3 dangerous in g++? Why is processing a sorted array faster than processing an unsorted array? MySQL my.cnf performance tuning recommendations