JavaScript Where To
The <script> Tag
In HTML, you put JavaScript code between <script> and </script> tags.
In the past, JavaScript examples sometimes had a "type" attribute like this: <script type="text/javascript">. But you don't really need that "type" attribute. JavaScript works just fine as the default scripting language in HTML.
JavaScript Functions and Events
A JavaScript function is like a block of code in JavaScript that does something when you tell it to.
For instance, you can make a function run when something happens, such as when a user presses a button.
JavaScript in <head> or <body>
You can insert as many scripts as you want into an HTML document.
You can put scripts in two places in an HTML page: inside the <body> or in the <head> section.
JavaScript in <head>
In this example, there's a JavaScript "function" placed in the "head" section of an HTML page.
The function gets triggered when someone clicks a button. Here's an instance: a JavaScript function is put inside the <head> part of an HTML page.
JavaScript in <body>
In this example, there is a JavaScript function placed inside the "body" section of an HTML page.
The function gets used when someone clicks a button.
Putting scripts at the end of the section makes websites load faster because reading and executing scripts can slow down how quickly a webpage appears on your screen.
External JavaScript
You can also put scripts in separate files:
External file: myScript.js
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
External scripts are handy when you want to use the same code on multiple web pages.
JavaScript files end with the .js file extension.
To add an external script, just place the script file's name in the "src" (source) attribute of the <script> tag:
You can insert an external script link in either the <head> or <body> section of your HTML code as per your preference.
The script will act as if it were placed right where the <script>
tag is..
External scripts should not have <script> tags inside them.
External JavaScript Advantages
Putting scripts in external files has some benefits.:
- It separates HTML and code
- It makes HTML and JavaScript easier to read and maintain
- Cached JavaScript files can speed up page loads
To include multiple script files on a single webpage, you should use multiple script tags.
Example
<script src="myScript1.js"></script>
<script src="myScript2.js"></script>
External References
You can include an external script in three different ways:
- With a full URL (a full web address)
- With a file path (like /js/)
- Without any path
In this example, we're using a complete web address (URL) to connect to a JavaScript file called myScript.js.