Using JavaScript
JavaScript is most commonly used for client-side scripting within an HTML document. As such, this section will focus on how to apply JavaScript in this way.
HTML provides a means of including JavaScript code in the form of the
<script>
element. Using the <script>
element, JavaScript can be included in a web page in two ways:
- Internal Script
- External Script
Note: It is no longer necessary to include "type = text/javascript" within the <script>
tag as JavaScript is the default scripting language in all modern browsers and in HTML5.
Internal Script
Internal scripts include JavaScript code directly in the markup by using the <script>
tag, like this:
<html>
<head>
<script>
document.write("Hello World!");
</script>
</head>
<body>
content goes here
</body>
</html>
This method is a good choice for quickly testing a solution or adding code that is specific to a particular page.
External Script
External scripts instruct the browser to download a separate JavaScript file and execute it in the page. The src attribute points to the script file like any other URL.
<html>
<head>
<script src="myscript.js">
</script>
</head>
<body>
content goes here
</body>
</html>
The myscript.js file would look like this:
document.write("Hello World!");
In most cases, this is the best solution for a few reasons:
- Placing the JavaScript code directly in the HTML file with an internal script makes the HTML files larger and harder to maintain
- JavaScript can easily be included in multiple pages just by including the same
<script>
tag - Most browsers cache JavaScript files so they don't have to download a script file twice when visiting another page that uses it