But, we need a working environment to run our scripts, and, just because this book is online, the browser is a good choice. We'll keep the amount of browser-specific commands (like
alert) to a minimum so that you don't spend time on them if you plan to concentrate on another environment like Node.JS. On the other hand, browser details are explained in detail in the next part of the tutorial.
So first, let's see how to attach a script to a webpage. For server-side environments, you can just execute it with a command like
"node my.js" for Node.JS.
The "script" tag
<!DOCTYPE HTML> <html> <body> <p>Before the script...</p> *!* <script> alert( 'Hello, world!' ); </script> */!* <p>...After the script.</p> </body> </html>
The modern markup
<script> tag has a few attributes that are rarely used nowadays, but we can find them in old code:
The type attribute:
: The old standard HTML4 required a script to have a type. Usually it was
The language attribute:
<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.
The script file is attached to HTML with the src attribute:
/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,
"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 then store it in its cache. After this, other pages that 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.
If src is set, the script content is ignored.
<script>tag can't have both the
srcattribute 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> 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