Javascript - <script> Element

Introduction

The primary method of inserting JavaScript into an HTML page is via the <script> element.

There are six attributes for the <script> element:

Attribute
Optional
Meaning
async

Optional

script should begin downloading immediately but should not prevent other actions such as downloading resources or waiting for other scripts to load.
Valid only for external script files.
charset

Optional

The character set of the code specified using the src attribute.
rarely used, because most browsers don't honor its value.
defer

Optional

execution of the script can safely be deferred until after the document's content has been completely parsed and displayed.
Valid only for external scripts.
language

Deprecated

indicate the scripting language being used by the code block ("JavaScript", "JavaScript 1.2", or "VBScript").
Most browsers ignore this attribute.
src
Optional
an external file that contains code to be executed.
type



Optional



Replaces language; indicates the content type (MIME type) of the scripting language being used by the code block.
Traditionally, this value has always been "text/javascript",
"text/javascript" and "text/ecmascript" are deprecated.
This attribute is safe to omit, as "text/javascript" is assumed when missing.

There are two ways to use the <script> element:

  • embed JavaScript code directly into the page or
  • include JavaScript from an external file.

To include inline JavaScript code, place JavaScript code inside the <script> element directly, as follows:

<script type="text/javascript"> 
    function sayHi(){ 
        console.log("Hi!"); 
    } 
</script> 

The JavaScript code contained inside a <script> element is interpreted from top to bottom.

When using inline JavaScript code, you cannot have the string "</script>" anywhere.

For example, the following code causes an error when loaded into a browser:

<script type="text/javascript"> 
    function sayScript(){ 
        console.log("</script>"); 
    } 
</script> 

The browser sees the string "</script>" as if it were the closing </script> tag.

To fix it, escape the "/" character:

<script type="text/javascript"> 
    function sayScript(){ 
        console.log("<\/script>"); 
    } 
</script> 

Exercise