JavaScript tag

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

<script> tag:

Any type of client side script can be written inside <script> tag in html. The script tag identifies a block of script code in the html page. It also loads a script file with src attribute.

The JavaScript code can also be embedded in <script> tag as shown below.

<script> tag example:

    //write JavaScript here..

Html 4.x requires type attribute in script tag. The type attribute is used to identify the language of script code embedded within script tag. This is specified as MIME type e.g. text/javascript, text/ecmascript, text/vbscript etc. So, for the JavaScript code, specify type="text/javascript" in the script tag in html 4.x page.

script tag in HTML 4.x:

<script type="text/javascript">

    //write JavaScript here..


Html 5 page does not require type attribute in the <script> tag, because in HTML 5 the default script language is JavaScript

External Script file:

If you don't want to write JavaScript between script tag in a web page then you can also write JavaScript code in a separate file with .js extension and include it in a web page using <script> tag and reference the file via src attribute.

<script src="/PathToScriptFile.js"></<script>

The script tag can appear any number of times in the <head> or <body> tag.

Script tag into <head> tag:

You can include script tag into head tag as shown below.

The browser loads all the scripts in head tag before loading and rendering body html. It is recommended to include scripts before ending body tag if scripts are not required while window is loading.

Script at the end of <body> tag:

Scripts can also be added at the end of body tag. This way you can be sure that all the web page resources are loaded and it is safe to interact with DOM.

Script at the end of <body> tag:

<!DOCTYPE html>

    <meta name="viewport" content="width=device-width" />
    <title>JavaScript Demo</title>
    <h1> JavaScript Tutorials</h1>
    <p>This is JavaScript sample.</p>
        <!--Some HTML here.. -->
        //write JavaScript code here..

    <script src="/PathToScriptFile.js"></<script> @* External JavaScript file *@

Thus, you can write JavaScript in script tag at appropriate places in a web page.

Points to Remember :

  1. JavaScript code must be written within <script> tag.
  2. External JavaScript file (.js) can be referenced using <script src="/PathToScriptFile.js"></script> where src attribute is used to specify the full path of .js file.
  3. Html5 standard does not required type="text/javascript" attribute, whereas prior html standards requires type attribute.
  4. The <script> tag can be added into <head> or <body> tag.
  5. The script included into <head> tag may not be able to access DOM elements because <head> loads before <body>. Write script before ending of </body> tag if script code needs to access DOM elements.