When adding JavaScript to an HTML page, you have a few different options for where to place your code.
script TagIn HTML, JavaScript code must be inserted between <script> and </script> tags.
<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>
Note: Older examples might use a type attribute:
<script type="text/javascript">. Thetypeattribute is no longer required, as JavaScript is the default scripting language in HTML.
A JavaScript function is a block of JavaScript code that can be executed when "called" for. For example, a function can be called when an event occurs, like when the user clicks a button.
(You will learn much more about functions and events in later chapters.)
head or bodyYou can place any number of scripts in an HTML document. Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both.
headIn this example, a JavaScript function is placed in the <head> section of an HTML page. The function is invoked (called) when a button is clicked.
<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<button type="button" onclick="myFunction()">Try it</button>
<p id="demo">A Paragraph</p>
bodyIn this example, a JavaScript function is placed in the <body> section of an HTML page. The function is also called when a button is clicked.
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
Best Practice: Placing scripts at the very bottom of the
<body>element improves display speed because script interpretation slows down the page rendering.
Scripts can also be placed in external files. This is extremely practical when the same code is used across many different web pages.
JavaScript files have the file extension .js.
To use an external script, put the name of the script file in the src (source) attribute of a <script> tag:
<script src="myScript.js"></script>
You can place an external script reference in <head> or <body> as you like. The script will behave as if it was located exactly where the <script> tag is located.
Important: External scripts cannot contain
<script>tags themselves. They only contain plain JavaScript code.
Placing scripts in external files has some significant advantages:
To add several script files to one page, just use several script tags:
<script src="myScript1.js"></script> <script src="myScript2.js"></script>
An external script can be referenced in 3 different ways:
1. With a full URL (a full web address)
<script src="https://www.example.com/js/myScript.js"></script>
2. With a file path (like /js/)
<script src="/js/myScript.js"></script>
3. Without any path (relative to current page)
<script src="myScript.js"></script>
What is the correct HTML for referring to an external JavaScript file named "myScript.js"?