html tutorial - <script> Tag in HTML - html5 - html code - html form
- The <script> element either holds inline scripting statements, or it fetch an outside script file through the src attribute.
- <script> tag belongs to Metadata content, Flow content and Phrasing content.
Syntax for <script> tag:
Differences between HTML 4.0.1 and HTML 5 for <script> tag in HTML:
- The "type" attribute is required.
- The "async" attribute not supported.
- "xml:space" is supported.
- The "type" attribute is optional.
- The "async" attribute is new to HTML5.
- "xml:space" is not supported.
Sample Coding for <script> tag:
Code Explanation for <script> tag:
- <p> tag id value has been defined as “para”.
- <script> tag is used to embed the executable script.
- The text Hello Wikitechy! will be included inside <p> tag which has the id as para.
Output for <script> tag:
- The text “Hello Wikitechy!” has been included inside <p> tag by using <script> tag.
Attributes of <script> tag:
|async||async||No||Yes||Defines that the script is executed only for external scripts.|
|charset||charset||Yes||Yes||Defines the character encoding used in an external script file.|
|defer||defer||Yes||Yes||Defines that the script is executed though the page has been finished parsing.|
|src||URL||Yes||Yes||Defines the URL of an external script file.|
|type||media_type||Yes||Yes||Defines the media type of the script.|
|xml:space||preserve||Yes||No||Defines whether whitespace in code have been preserved.|
Browser Support for <script> tag in HTML:
Tips and Notes
- If the "src" attribute is present, the <script> element must be empty.
- There are many ways an external script should be executed:
- async="async": The script can be executed while the page continues the parsing.
- defer="defer": The script is executed when the page has finished parsing.
- If neither async or defer is present: The script is fetched and executed immediately, before the browser continues parsing the page.