But we need a working environment to run our scripts, and, just because this book is online, the browser a good choice. We’ll keep the amount of browser-specific commands (like
alert) to minimum, so that you don’t spend time on them if you plan to concentrate on another environment like Node.JS. From the other hand, browser details are explained in detail in the next part of the tutorial. So
So first let’s see how to attach a script to the webpage. For server-side environments you can just execute it with a command like
"node my.js" for Node.JS.
You can run the example clicking on a “Play” button in it’s right-top corner.
<script> tag has a few attributes that are rarely used nowadays, but we can find them in the old code:
The old standard HTML4 required a script to have the type. Usually it was
typeby default, no attribute is required.
- Comments before and after scripts.
In really ancient books and guides, one may find comments inside
<script>, like this:
These comments were supposed to hide the code from an old browser that did’t know about a
<script>tag. But all browsers born in the past 15+ years don’t have any issues. It is only mentioned here, because it serves as a sign. If you see that somewhere – that code is probably really old and not worth looking into.
The script file is attached to HTML like this:
/path/to/script.js is an absolute path to the file with the script (from the site root).
It is also possible to provide a path relative to the current page. For instance,
src="script.js" would mean a file
"script.js" from the current folder.
We can give a full URL al 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 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 then store in its cache.
After it, other pages which want the same script will take it from the cache instead of downloading it. So the file is actually downloaded only once.
That saves traffic and makes pages faster.
srcis set, the script content is ignored.
<script> tag may not have both an
src and the 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 it’s 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