The Script Tag

<!DOCTYPE HTML>
<html>

<body>

<p>Before the script...</p>

<script>
alert( 'Hello, world!' );
</script>

<p>...After the script.</p>

</body>

</html>

You write your JS code inside the <script> tag in the HTML document. You can place this script tag anywhere in your HTML code but good practice is to put them just before the closing tag of the body. The <script> tag contains JavaScript code which is automatically executed when the browser meets the tag.

The <script> tag has a few attributes that are rarely used nowadays -

External Script File

If we have a lot of JavaScript code, we can put it into a separate file. The script file is attached to HTML with the src attribute:

<script src="/path/to/script.js"></script>

Here, the path is the relative to the HTML file.

We can give a full URL as well, for instance:

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.2.0/lodash.js"></script>

To attach several scripts, use multiple tags:

<script src="/js/script1.js"></script>
<script src="/js/script2.js"></script>
…

A single <script> tag can’t have both the src attribute and the code inside. If src is set, the script content is ignored.