<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>The script tag</title> </head> <body> <p>A random paragraph before the script tag</p> <script> alert('Hi!!!'); </script> </body> </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 (
<script language='...'>), 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:
<script src="/js/script1.js"></script> <script src="/js/script2.js"></script> ...
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.
<script src="file.js"> // this content will be ignored, since you specified the src attribute alert('You can't see me 🙈'); </script>
Do like this:
<script src="script.js"></script> <script> alert('Now you see me 😃'); </script>