February 01, 2020 • ☕️ 2 min read
1<!DOCTYPE html>2<html lang="en">3 <head>4 <meta charset="UTF-8" />5 <meta name="viewport" content="width=device-width, initial-scale=1.0" />6 <meta http-equiv="X-UA-Compatible" content="ie=edge" />7 <title>The script tag</title>8 </head>9 <body>10 <p>A random paragraph before the script tag</p>1112 <script>13 alert('Hi!!!');14 </script>15 </body>16</html>
This tag contains JS code that is automatically executed when the browser processes it.
Three common examples of old way of writing JS code are the
language attributes, in addition to the practice of using comments inside scripts.
Back in the old days, HTML4 required a script to include a type, usually
With the release of HTML5, this attribute is no longer required.
As the name of the attribute specifies, this attribute was meant to show the language of the script.
<script> tag, there is no need to use it.
Modern browsers are fully equipped to process JS code and this trick has become obsolete.
When you write code, it is important to keep in mind clean code principles like DRY (don't repeat yourself) and organizing the file structure of a codebase is fundamental.
If you notice that the code inside your script file becomes very long, that is the sign that it can be broken up into separate scripts.
You can attach script file to HTML using the
src attribute and providing an absolute or relative path to the script that you want to import, in addition to a full URL:
relative path (here, it means that the script is in the current folder):
Finally, if you want to attach several scripts, use multiple tags:
1<script src="/js/script1.js"></script>2<script src="/js/script2.js"></script>3...
A common practice when importing script files into HTML is to put into HTML only the simple scripts and organize the complex ones into separate files. Organizing your scripts into separate files can be extremely beneficial, since the browser will download it only once and store it in its cache. Then other pages can reference the same script from the browser's cache instead of downloading it again. That reduces traffic and makes pages faster.
Always keep in mind that, if a script contains a
src attribute, the content of that script is ignored.
Basically, a single
<script> tag can’t have both the
src attribute and code inside of it.
We must choose either an external
<script src='...'> or a regular
<script> with code.
1<script src="file.js">2 // this content will be ignored, since you specified the src attribute3 alert('You can't see me 🙈');4</script>
Do like this:
1<script src="script.js"></script>2<script>3 alert('Now you see me 😃');4</script>