But we need a working environment to run our scripts and, since this book is online, the browser is a good choice. We’ll keep the amount of browser-specific commands (like
So first, let’s see how we attach a script to a webpage. For server-side environments (like Node.js), you can execute the script with a command like
The “script” tag
You can run the example by clicking the “Play” button in the right-top corner of the box above.
<script> tag has a few attributes that are rarely used nowadays but can still be found in old code:
The old HTML standard, HTML4, required a script to have a
type. Usually it was
- Comments before and after scripts.
In really ancient books and guides, you may find comments inside
<script>tags, like this:
<script>tag. Since browsers released in the last 15 years don’t have this issue, this kind of comment can help you identify really old code.
Script files are attached to HTML with the
/path/to/script.js is an absolute path to the script from the site root. One can also provide a relative path from the current page. For instance,
src="script.js", just like
src="./script.js", would mean a file
"script.js" in the current folder.
We can give a full URL as well. For instance:
To attach several scripts, use multiple tags:
<script src="/js/script1.js"></script> <script src="/js/script2.js"></script> …
As a rule, only the simplest scripts are put into HTML. More complex ones reside in separate files.
The benefit of a separate file is that the browser will download it and store it in its cache.
Other pages that reference the same script will take it from the cache instead of downloading it, so the file is actually downloaded only once.
That reduces traffic and makes pages faster.
srcis set, the script content is ignored.
<script> tag can’t have both the
src attribute and code inside.
This won’t work:
<script src="file.js"> alert(1); // the content is ignored, because src is set </script>
We must choose either an external
<script src="…"> or a regular
<script> with code.
The example above can be split into two scripts to work:
<script src="file.js"></script> <script> alert(1); </script>
- We can use a
languageattributes are not required.
- A script in an external file can be inserted with
<code>tag, for several lines – wrap them in
<pre>tag, for more than 10 lines – use a sandbox (plnkr, jsbin, codepen…)