[javascript] Where should I put <script> tags in HTML markup?

When embedding JavaScript in an HTML document, where is the proper place to put the <script> tags and included JavaScript? I seem to recall that you are not supposed to place these in the <head> section, but placing at the beginning of the <body> section is bad, too, since the JavaScript will have to be parsed before the page is rendered completely (or something like that). This seems to leave the end of the <body> section as a logical place for <script> tags.

So, where is the right place to put the <script> tags?

(This question references this question, in which it was suggested that JavaScript function calls should be moved from <a> tags to <script> tags. I'm specifically using jQuery, but more general answers are also appropriate.)

This question is related to javascript jquery html

The answer is


Just before the closing body tag, as stated on

http://developer.yahoo.com/performance/rules.html#js_bottom

Put Scripts at the Bottom

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.


It makes more sense to me to include the script after the HTML. Because most of the time I need the Dom to load before I execute my script. I could put it in the head tag but I don't like all the Document loading listener overhead. I want my code to be short and sweet and easy to read.

I've heard old versions of safari was quarky when adding your script outside of the head tag but I say who cares. I don't know anybody using that old crap do you.

Good question by the way.


The modern approach in 2019 is using ES6 module type scripts.

<script type="module" src="..."></script>

By default, modules are loaded asynchronously and defered. i.e. you can place them anywhere and they will load in parallel and execute when the page finishes loading.

The differences between a script and a module are described here:

https://stackoverflow.com/a/53821485/731548

The execution of a module compared to a script is described here:

https://developers.google.com/web/fundamentals/primers/modules#defer

Support is shown here:

https://caniuse.com/#feat=es6-module


Depending on the script and its usage the best possible (in terms of page load and rendering time) may be to not use a conventional <script>-tag per se, but to dynamically trigger the loading of the script asynchronously.

There are some different techniques, but the most straight forward is to use document.createElement("script") when the window.onload event is triggered. Then the script is loaded first when the page itself has rendered, thus not impacting the time the user has to wait for the page to appear.

This naturally requires that the script itself is not needed for the rendering of the page.

For more information, see the post Coupling async scripts by Steve Souders (creator of YSlow but now at Google).


  • If you still care a lot about support and performance in IE<10, it's best to ALWAYS make your script tags the last tags of your HTML body. That way, you're certain that the rest of the DOM has been loaded and you won't block and rendering.

  • If you don't care too much anymore about IE<10, you might want to put your scripts in the head of your document and use defer to ensure they only run after your DOM has been loaded (<script type="text/javascript" src="path/to/script1.js" defer></script>). If you still want your code to work in IE<10, don't forget to wrap your code in a window.onload even, though!


If you are using JQuery then put the javascript wherever you find it best and use $(document).ready() to ensure that things are loaded properly before executing any functions.

On a side note: I like all my script tags in the <head> section as that seems to be the cleanest place.


Just before the closing body tag, as stated on

http://developer.yahoo.com/performance/rules.html#js_bottom

Put Scripts at the Bottom

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.


XHTML Won't Validate if the script is anywhere other than within the head element. turns out it can be everywhere.

You can defer the execution with something like jQuery so it doesn't matter where it's placed (except for a small performance hit during parsing).


If you are using JQuery then put the javascript wherever you find it best and use $(document).ready() to ensure that things are loaded properly before executing any functions.

On a side note: I like all my script tags in the <head> section as that seems to be the cleanest place.


I think it depends on the webpage execution. If the page that you want to display can not displayed properly without loading JavaScript first then you should include JavaScript file first. But If you can display/render a webpage without initially download JavaScript file, then you should put JavaScript code at the bottom of the page. Because it will emulate a speedy page load, and from an user's point of view it would seems like that page is loading faster.


Including scripts at the end is mainly used where the content/ styles of the website is to be shown first.

including the scripts in the head loads the scripts early and can be used before the loading of the whole web site.

if the scripts are entered at last the validation will happen only after the loading of the entire styles and design which is not appreciated for fast responsive websites.


XHTML Won't Validate if the script is anywhere other than within the head element. turns out it can be everywhere.

You can defer the execution with something like jQuery so it doesn't matter where it's placed (except for a small performance hit during parsing).


If you are using JQuery then put the javascript wherever you find it best and use $(document).ready() to ensure that things are loaded properly before executing any functions.

On a side note: I like all my script tags in the <head> section as that seems to be the cleanest place.


  • If you still care a lot about support and performance in IE<10, it's best to ALWAYS make your script tags the last tags of your HTML body. That way, you're certain that the rest of the DOM has been loaded and you won't block and rendering.

  • If you don't care too much anymore about IE<10, you might want to put your scripts in the head of your document and use defer to ensure they only run after your DOM has been loaded (<script type="text/javascript" src="path/to/script1.js" defer></script>). If you still want your code to work in IE<10, don't forget to wrap your code in a window.onload even, though!


The best place to write your JavaScript code is at the end of the document after or right before the </body> tag to load the document first and then execute js code.

<script> ... your code here ... </script>
</body>

And if you write in JQuery the following can be in the head document and it will execute after the document loads:

<script>
$(document).ready(function(){
   //your code here...
});
</script>

I think it depends on the webpage execution. If the page that you want to display can not displayed properly without loading JavaScript first then you should include JavaScript file first. But If you can display/render a webpage without initially download JavaScript file, then you should put JavaScript code at the bottom of the page. Because it will emulate a speedy page load, and from an user's point of view it would seems like that page is loading faster.


The best place to put <script> tag is before closing </body> tag, so the downloading and executing it doesn't block the browser to parse the html in document,

Also loading the js files externally has it's own advantages like it will be cached by browsers and can speed up page load times, it separates the HTML and JavaScript code and help to manage the code base better.

but modern browsers also support some other optimal ways like async and defer to load external javascript files.

Async and Defer

Normally HTML page execution starts line by line. When an external JavaScript element is encountered, HTML parsing is stopped until a JavaScript is download and ready for execution. This normal page execution can be changed using defer and async attribute.

Defer

When a defer attribute is used, JavaScript is downloaded parallelly with HTML parsing but will be execute only after full HTML parsing is done.

<script src="/local-js-path/myScript.js" defer></script>

Async

When async attribute is used, JavaScript is downloaded as soon as the script is encountered and after the download, it will be executed asynchronously (parallelly) along with HTML parsing.

<script src="/local-js-path/myScript.js" async></script>

When to use which attributes

  • If your script is independent of other scripts and is modular, use async.
  • If you are loading script1 and script2 with async, both will run
    parallelly along with HTML parsing, as soon as they are downloaded
    and available.
  • If your script depends on another script then use defer for both:
  • When script1 and script2 are loaded in that order with defer, then script1 is guaranteed to execute first,
  • Then script2 will execute after script1 is fully executed.
  • Must do this if script2 depends on script1.
  • If your script is small enough and is depended by another script of type async then use your script with no attributes and place it above all the async scripts.

reference:knowledgehills.com


You can place most of <script> references at the end of <body>,
But If there are active components on your page which are using external scripts,
then their dependency (js files) should come before that (ideally in head tag).


The conventional (and widely accepted) answer is "at the bottom", because then the entire DOM will have been loaded before anything can start executing.

There are dissenters, for various reasons, starting with the available practice to intentionally begin execution with a page onload event.


<script src="myjs.js"></script>
</body>

script tag should be use always before body close or Bottom in HTML file.

Page will load with html and css and later js will load.

check this if require : http://stevesouders.com/hpws/rule-js-bottom.php


Depends, if you are loading a script that's necessary to style your page / using actions in your page (like click of a button) then you better place it on the top. If your styling is 100% CSS and you have all fallback options for the button actions then you can place it in the bottom.

Or best thing (if that's not a concern) is you can make a modal loading box, place your javascript at the bottom of your page and make it disappear when the last line of your script gets loaded. This way you can avoid users using actions in your page before the scripts are loaded. And also avoid the improper styling.


Non-blocking script tags can be placed just about anywhere:

<script src="script.js" async></script>
<script src="script.js" defer></script>
<script src="script.js" async defer></script>
  • async script will be executed asynchronously as soon as it is available
  • defer script is executed when the document has finished parsing
  • async defer script falls back to the defer behavior if async is not supported

Such scripts will be executed asynchronously/after document ready, which means you cannot do this:

<script src="jquery.js" async></script>
<script>jQuery(something);</script>
<!--
  * might throw "jQuery is not defined" error
  * defer will not work either
-->

Or this:

<script src="document.write(something).js" async></script>
<!--
  * might issue "cannot write into document from an asynchronous script" warning
  * defer will not work either
-->

Or this:

<script src="jquery.js" async></script>
<script src="jQuery(something).js" async></script>
<!--
  * might throw "jQuery is not defined" error (no guarantee which script runs first)
  * defer will work in sane browsers
-->

Or this:

<script src="document.getElementById(header).js" async></script>
<div id="header"></div>
<!--
  * might not locate #header (script could fire before parser looks at the next line)
  * defer will work in sane browsers
-->

Having said that, asynchronous scripts offer these advantages:

  • Parallel download of resources:
    Browser can download stylesheets, images and other scripts in parallel without waiting for a script to download and execute.
  • Source order independence:
    You can place the scripts inside head or body without worrying about blocking (useful if you are using a CMS). Execution order still matters though.

It is possible to circumvent the execution order issues by using external scripts that support callbacks. Many third party JavaScript APIs now support non-blocking execution. Here is an example of loading the Google Maps API asynchronously.


The standard advice, promoted by the Yahoo! Exceptional Performance team, is to put the <script> tags at the end of the document body so they don't block rendering of the page.

But there are some newer approaches that offer better performance, as described in this answer about the load time of the Google Analytics JavaScript file:

There are some great slides by Steve Souders (client-side performance expert) about:

  • Different techniques to load external JavaScript files in parallel
  • their effect on loading time and page rendering
  • what kind of "in progress" indicators the browser displays (e.g. 'loading' in the status bar, hourglass mouse cursor).

You can add JavaScript code in an HTML document by employing the dedicated HTML tag <script> that wraps around JavaScript code.

The <script> tag can be placed in the <head> section of your HTML, in the <body> section, or after the </body> close tag, depending on when you want the JavaScript to load.

Generally, JavaScript code can go inside of the document <head> section in order to keep them contained and out of the main content of your HTML document.

However, if your script needs to run at a certain point within a page’s layout — like when using document.write to generate content — you should put it at the point where it should be called, usually within the <body> section.


The standard advice, promoted by the Yahoo! Exceptional Performance team, is to put the <script> tags at the end of the document body so they don't block rendering of the page.

But there are some newer approaches that offer better performance, as described in this answer about the load time of the Google Analytics JavaScript file:

There are some great slides by Steve Souders (client-side performance expert) about:

  • Different techniques to load external JavaScript files in parallel
  • their effect on loading time and page rendering
  • what kind of "in progress" indicators the browser displays (e.g. 'loading' in the status bar, hourglass mouse cursor).

Depending on the script and its usage the best possible (in terms of page load and rendering time) may be to not use a conventional <script>-tag per se, but to dynamically trigger the loading of the script asynchronously.

There are some different techniques, but the most straight forward is to use document.createElement("script") when the window.onload event is triggered. Then the script is loaded first when the page itself has rendered, thus not impacting the time the user has to wait for the page to appear.

This naturally requires that the script itself is not needed for the rendering of the page.

For more information, see the post Coupling async scripts by Steve Souders (creator of YSlow but now at Google).


XHTML Won't Validate if the script is anywhere other than within the head element. turns out it can be everywhere.

You can defer the execution with something like jQuery so it doesn't matter where it's placed (except for a small performance hit during parsing).


The conventional (and widely accepted) answer is "at the bottom", because then the entire DOM will have been loaded before anything can start executing.

There are dissenters, for various reasons, starting with the available practice to intentionally begin execution with a page onload event.


Just before the closing body tag, as stated on

http://developer.yahoo.com/performance/rules.html#js_bottom

Put Scripts at the Bottom

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.


Including scripts at the end is mainly used where the content/ styles of the website is to be shown first.

including the scripts in the head loads the scripts early and can be used before the loading of the whole web site.

if the scripts are entered at last the validation will happen only after the loading of the entire styles and design which is not appreciated for fast responsive websites.


You can place most of <script> references at the end of <body>,
But If there are active components on your page which are using external scripts,
then their dependency (js files) should come before that (ideally in head tag).


Depending on the script and its usage the best possible (in terms of page load and rendering time) may be to not use a conventional <script>-tag per se, but to dynamically trigger the loading of the script asynchronously.

There are some different techniques, but the most straight forward is to use document.createElement("script") when the window.onload event is triggered. Then the script is loaded first when the page itself has rendered, thus not impacting the time the user has to wait for the page to appear.

This naturally requires that the script itself is not needed for the rendering of the page.

For more information, see the post Coupling async scripts by Steve Souders (creator of YSlow but now at Google).


Script blocks DOM load untill it's loaded and executed.

If you place scripts at the end of <body> all of DOM has chance to load and render (page will "display" faster). <script> will have access to all of those DOM elements.

In other hand placing it after <body> start or above will execute script (where there's still no DOM elements).

You are including jQuery which means you can place it wherever you wish and use .ready()


<script src="myjs.js"></script>
</body>

script tag should be use always before body close or Bottom in HTML file.

Page will load with html and css and later js will load.

check this if require : http://stevesouders.com/hpws/rule-js-bottom.php


The conventional (and widely accepted) answer is "at the bottom", because then the entire DOM will have been loaded before anything can start executing.

There are dissenters, for various reasons, starting with the available practice to intentionally begin execution with a page onload event.


Just before the closing body tag, as stated on

http://developer.yahoo.com/performance/rules.html#js_bottom

Put Scripts at the Bottom

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.


The best place to write your JavaScript code is at the end of the document after or right before the </body> tag to load the document first and then execute js code.

<script> ... your code here ... </script>
</body>

And if you write in JQuery the following can be in the head document and it will execute after the document loads:

<script>
$(document).ready(function(){
   //your code here...
});
</script>

XHTML Won't Validate if the script is anywhere other than within the head element. turns out it can be everywhere.

You can defer the execution with something like jQuery so it doesn't matter where it's placed (except for a small performance hit during parsing).


The standard advice, promoted by the Yahoo! Exceptional Performance team, is to put the <script> tags at the end of the document body so they don't block rendering of the page.

But there are some newer approaches that offer better performance, as described in this answer about the load time of the Google Analytics JavaScript file:

There are some great slides by Steve Souders (client-side performance expert) about:

  • Different techniques to load external JavaScript files in parallel
  • their effect on loading time and page rendering
  • what kind of "in progress" indicators the browser displays (e.g. 'loading' in the status bar, hourglass mouse cursor).

Depends, if you are loading a script that's necessary to style your page / using actions in your page (like click of a button) then you better place it on the top. If your styling is 100% CSS and you have all fallback options for the button actions then you can place it in the bottom.

Or best thing (if that's not a concern) is you can make a modal loading box, place your javascript at the bottom of your page and make it disappear when the last line of your script gets loaded. This way you can avoid users using actions in your page before the scripts are loaded. And also avoid the improper styling.


The modern approach in 2019 is using ES6 module type scripts.

<script type="module" src="..."></script>

By default, modules are loaded asynchronously and defered. i.e. you can place them anywhere and they will load in parallel and execute when the page finishes loading.

The differences between a script and a module are described here:

https://stackoverflow.com/a/53821485/731548

The execution of a module compared to a script is described here:

https://developers.google.com/web/fundamentals/primers/modules#defer

Support is shown here:

https://caniuse.com/#feat=es6-module


Non-blocking script tags can be placed just about anywhere:

<script src="script.js" async></script>
<script src="script.js" defer></script>
<script src="script.js" async defer></script>
  • async script will be executed asynchronously as soon as it is available
  • defer script is executed when the document has finished parsing
  • async defer script falls back to the defer behavior if async is not supported

Such scripts will be executed asynchronously/after document ready, which means you cannot do this:

<script src="jquery.js" async></script>
<script>jQuery(something);</script>
<!--
  * might throw "jQuery is not defined" error
  * defer will not work either
-->

Or this:

<script src="document.write(something).js" async></script>
<!--
  * might issue "cannot write into document from an asynchronous script" warning
  * defer will not work either
-->

Or this:

<script src="jquery.js" async></script>
<script src="jQuery(something).js" async></script>
<!--
  * might throw "jQuery is not defined" error (no guarantee which script runs first)
  * defer will work in sane browsers
-->

Or this:

<script src="document.getElementById(header).js" async></script>
<div id="header"></div>
<!--
  * might not locate #header (script could fire before parser looks at the next line)
  * defer will work in sane browsers
-->

Having said that, asynchronous scripts offer these advantages:

  • Parallel download of resources:
    Browser can download stylesheets, images and other scripts in parallel without waiting for a script to download and execute.
  • Source order independence:
    You can place the scripts inside head or body without worrying about blocking (useful if you are using a CMS). Execution order still matters though.

It is possible to circumvent the execution order issues by using external scripts that support callbacks. Many third party JavaScript APIs now support non-blocking execution. Here is an example of loading the Google Maps API asynchronously.


The conventional (and widely accepted) answer is "at the bottom", because then the entire DOM will have been loaded before anything can start executing.

There are dissenters, for various reasons, starting with the available practice to intentionally begin execution with a page onload event.


Script blocks DOM load untill it's loaded and executed.

If you place scripts at the end of <body> all of DOM has chance to load and render (page will "display" faster). <script> will have access to all of those DOM elements.

In other hand placing it after <body> start or above will execute script (where there's still no DOM elements).

You are including jQuery which means you can place it wherever you wish and use .ready()


The standard advice, promoted by the Yahoo! Exceptional Performance team, is to put the <script> tags at the end of the document body so they don't block rendering of the page.

But there are some newer approaches that offer better performance, as described in this answer about the load time of the Google Analytics JavaScript file:

There are some great slides by Steve Souders (client-side performance expert) about:

  • Different techniques to load external JavaScript files in parallel
  • their effect on loading time and page rendering
  • what kind of "in progress" indicators the browser displays (e.g. 'loading' in the status bar, hourglass mouse cursor).

It makes more sense to me to include the script after the HTML. Because most of the time I need the Dom to load before I execute my script. I could put it in the head tag but I don't like all the Document loading listener overhead. I want my code to be short and sweet and easy to read.

I've heard old versions of safari was quarky when adding your script outside of the head tag but I say who cares. I don't know anybody using that old crap do you.

Good question by the way.


If you are using JQuery then put the javascript wherever you find it best and use $(document).ready() to ensure that things are loaded properly before executing any functions.

On a side note: I like all my script tags in the <head> section as that seems to be the cleanest place.


The best place to put <script> tag is before closing </body> tag, so the downloading and executing it doesn't block the browser to parse the html in document,

Also loading the js files externally has it's own advantages like it will be cached by browsers and can speed up page load times, it separates the HTML and JavaScript code and help to manage the code base better.

but modern browsers also support some other optimal ways like async and defer to load external javascript files.

Async and Defer

Normally HTML page execution starts line by line. When an external JavaScript element is encountered, HTML parsing is stopped until a JavaScript is download and ready for execution. This normal page execution can be changed using defer and async attribute.

Defer

When a defer attribute is used, JavaScript is downloaded parallelly with HTML parsing but will be execute only after full HTML parsing is done.

<script src="/local-js-path/myScript.js" defer></script>

Async

When async attribute is used, JavaScript is downloaded as soon as the script is encountered and after the download, it will be executed asynchronously (parallelly) along with HTML parsing.

<script src="/local-js-path/myScript.js" async></script>

When to use which attributes

  • If your script is independent of other scripts and is modular, use async.
  • If you are loading script1 and script2 with async, both will run
    parallelly along with HTML parsing, as soon as they are downloaded
    and available.
  • If your script depends on another script then use defer for both:
  • When script1 and script2 are loaded in that order with defer, then script1 is guaranteed to execute first,
  • Then script2 will execute after script1 is fully executed.
  • Must do this if script2 depends on script1.
  • If your script is small enough and is depended by another script of type async then use your script with no attributes and place it above all the async scripts.

reference:knowledgehills.com


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 jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

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