Script Tag
The <script> tag has three applications:
- When used in the <head> element, it can contain JavaScript statements.
- When used in the <body> element, it can contain JavaScript statements. This use is not recommended.
- When used in the <head> element, it can be used to load external JavaScript files.
Contents
In the <head> Element
<!doctype html> <html> <head> <script> window.alert("JavaScript is active"); </script> </head> <body> </body> </html>
In the <body> Element
Again, this usage is not recommended. Best practices dictate that content and function remain separate.
<!doctype html> <html> <head> </head> <body> <button onclick="alert('JavaScript is active');">Click me</button> </body> </html>
In the <head> Element to Load External JavaScript Files
<!doctype html> <html> <head> <script src="myscript.js"></script> </head> <body> </body> </html>
This method does not work within the <body> tag. If you want to load external JavaScript files, you must do so from within the <head> element.
HTML Compliance
HTML5
In Javascript, the proper notation for HTML5 has no attributes:
<script> ...JavaScript statements... </script>
HTML4
When used in HTML4 or XHTML, the <script> tag must include the type attribute:
<script type="text/javascript"> ...JavaScript statements... </script>
Deprecated Attributes
At one point, the language="JavaScript" attribute was required. It has long been deprecated and should not be used.