In this section, we will learn what HTML <script> element is and how to use it.
Scripting in HTML: What is <script> Tag in HTML and How to use JavaScript in HTML?
HTML <script> element is used to bring JavaScript programs into an HTML document.
HTML <script> element is used in two ways:
- If the JavaScript source code is already written in a file somewhere outside of the HTML document, we can use the `src` attribute of the <script> element and set the address of that external JavaScript file as the value of this attribute. Browsers then send a request to that URL to get back the JavaScript file and load it in the HTML document.
- On the other hand, if we want to write JavaScript codes directly in an HTML document, we can use the body of the <script> element. Basically, this body is the place where we can write JavaScript codes and browsers run those scripts when the page was loaded in.
Notes:
- It’s a good practice to put <script> element within the body of HTML <body> element and right before its closing tag `</body>`.
- It’s important to note that a <script> element using the `src` attribute should not include additional JavaScript code between the <script> and </script> tags. If both are provided, the script file is downloaded and executed while the inline code is ignored.
- Sometimes users disable the use of JavaScript in their browsers. In such cases, your JavaScript program (the content of the <script> element) won’t be executed. If this will harm your HTML document, you can use HTML <noscript> element to alert users about this problem.
HTML <script> Tag Syntax:
<script type = “text/javascript”> </script>
HTML <script> Tag Values
The value we set in the body of HTML <script> element is the script codes that we want it to be executed in that browser when the page is loaded.
Example: using JavaScript in HTML
See the Pen using JavaScript in HTML by Omid Dehghan (@odehghan) on CodePen.
Example: HTML inline JavaScript
See the Pen HTML inline JavaScript by Omid Dehghan (@odehghan) on CodePen.