Java Reference
In-Depth Information
Where do mY sCripts go?
Inserting JavaScript into a web page is much like inserting any other HTML content; you use tags
to mark the start and end of your script code. The element you use to do this is <script/> . This
tells the browser that the following chunk of text, bounded by the closing </script> tag, is not
HTML to be displayed, but rather script code to be processed. The chunk of code surrounded by
the <script> and </script> tags is called a script block . Here's an example:
<script>
// JavaScript goes here
</script>
Basically, when the browser spots <script> tags, instead of trying to display the contained text to
the user, it uses the browser's JavaScript engine to run the code's instructions. Of course, the code
might give instructions about changes to the way the page is displayed or what is shown in the page,
but the text of the code itself is never shown to the user.
You can put the <script/> element inside the header (between the <head> and </head> tags)
or inside the body (between the <body> and </body> tags) of the HTML page. However,
although you can put them outside these areas—for example, before the <html> tag or after
the </html> tag—this is not permitted in the web standards and so is considered bad practice.
Today's JavaScript developers typically add their <script/> elements directly before the
</body> tag.
The <script/> element has a type attribute that tells the browser what type of text is contained
within the element. For JavaScript, the best practice is to omit the type attribute (browsers
automatically assume that any <script/> element without a type attribute is JavaScript). We used
to always set the type attribute to text/javascript , but with the introduction of the HTML5
specification, it is no longer considered good practice to do so. Only include the type attribute if the
<script/> element contains something other than JavaScript.
Note The <script/> element can be used for more than just JavaScript.
Some JavaScript‐based templating engines use <script/> elements to contain
snippets of HTML.
linking to an external Javascript file
The <script/> element has another arrow in its quiver: the capability to specify that the JavaScript
code is not inside the web page, but inside a separate file. You should give any external files the
file extension .js . Though it's not compulsory, it does make it easier for you to work out what is
contained in each of your files.
To link to an external JavaScript file, you need to create a <script/> element as described earlier
and use its src attribute to specify the location of the external file. For example, imagine you've
 
Search WWH ::




Custom Search