Adding a Script in an HTML Document
02-02-18 Course- Javascript_Simple
You can add a JavaScript script in an HTML document by using the <script> and </script> tags, which are used to enclose a script. When an HTML document containing the <script> and </script> tags is loaded in a Web browser, the browser processes the content enclosed within these tags as a script code.
Similar to other HTML tags, the <script> tag also has various attributes. The important attributes of the <script> tag are given as follows:
- type : Refers to the Multipurpose Internet Mail Extensions (MIME) type of the script where MIME is basically a internet protocol that can be used for the transmission of data such as audio, video, images, over the internet. The type attribute can have text/ecmascript, text/javascript, text/vbscript, application/ecmascript, or application/javascript as its value. As per the World Wide Web Consortium (W3C), it is mandatory to specify the type attribute.
- language: Refers to the scripting language that is to be used for the script. This attribute can have values, such as javascript or vbscript. Note that this attribute is not required if you have specified the type attribute. However, for backward compatibility with older versions of Web browsers that may not support the type attribute, you can specify both the attributes.
- src: Refers to the Uniform Locator (URL) of another file that has a script. This attribute is used for specifying external script files.
- defer: Specifies that no script is generated until the page completes the parsing (syntactical checks) and rendering. This attribute tells the browser to wait until the page is ready to execute the script.
- async: Refers to the Boolean attribute that is used to execute the script asynchronously without blocking. The async attribute has been newly introduced in the HTML 5 and used in conjunction with the <script> tag. It takes two values: true and false. If the async attribute is set to true, then the script executes while parsing. In case, the attribute is set to false, then it executes the script after finishing the parsing and rendering of a Web page.
You can add a script in an HTML document by either creating a script within the document or linking an external script file with the HTML document.
Let’s first learn how to create a script inside an HTML document.