Javascript is the last of the client-side technologies we will be covering in this class. After XHTMl and CSS, it is the third most prevalent technology on the web today.
Javascript has nothing to do with Java. Javascript is actually based on a language called ECMAScript, so if you must use the wrong name, call it ECMAScript. But whatever you do, never mistakenly use the term “Java” when you mean to say “Javascript”… it’s a sign of web dev ignorance to do so.
Similarly to CSS, Javascript should always be written in an external file whenever possible. And like CSS, Javascript can be put in your XHTML code in three different places:
1) nested within the <head> tag
2) nested within the <body> tag
3) as an attribute of almost any XHTML element
Here are examples of each of these placements:
Nested within the <head> tag
... <head> ... <script type="text/javascript" src="scripts/something.js"></script> ... </head> ...
Click to view a page using this example code
Nested within the <body> tag
... <body> ... <script type="text/javascript" src="scripts/something.js"></script> ... </body> ...
Click to view a page using this example code
As an attribute of an XHTML element
...
<a href="#" onclick="alert('Hello again!');">Click me please</a>
...
Click to view a page using this example code
Internal vs. External Scripts
Just as with CSS, as far as the web browser is concerned, an external script file is equivalent to an internal script. So in the examples above, you could replace any of the external <script> tags with an internal script and get the same results in the browser.
Here is the example of a script nested within the <head> element, as shown above, but this time using an internal script. The important thing to notice is that the syntax of the <script> tag is basically the same, but the src attribute is removed and Javascript code is placed between the start and end <script> tags:
...
<head>
...
<script type="text/javascript">
alert('Hello World!');
</script>
...
</head>
...
Click to view a page using this example code
For the same reasons as with CSS, you are encouraged to use external Javscripts whenever possible. This affords you a clear separation of markup (XHTML) from presentation (CSS) from behavior (Javascript).
No related posts.