JS Where To
The Tag
JavaScript code is entered into HTML in between the <script> and </script> elements.
Example
A type attribute might be used in older JavaScript examples, such as <script type=”text/javascript”>.
There is no need for the type attribute. The default programming language in HTML is called JavaScript.
JavaScript Functions and Events
A block of JavaScript code that can be run when “called” for is known as a JavaScript function.
A function could be mentioned for instance, whenever an event takes place, such as a button click by the user.
Later chapters will cover functions and events in much greater detail.
JavaScript in or
An HTML document can contain any number of scripts.
Scripts can be inserted into an HTML page’s <head>, <body>, or both sections.
JavaScript in
In this instance, an HTML page’s <head> element contains a JavaScript function.
When a button is clicked, the function is triggered, or called:
Example
Demo JavaScript in Head
A Paragraph
JavaScript in
In this instance, an HTML page’s <body> element contains a JavaScript function.
When a button is clicked, the function is triggered, or called:
Example
Demo JavaScript in Body
A Paragraph
External JavaScript
External file: myScript.js
External file: myScript.js
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
In situations where the same code is utilized across multiple web pages, external scripts become useful.
The.js file extension is used for JavaScript files.
Put the name of the external script in the src (source) property of a <script> element in order to use it:
Example
You have the option to reference an external script inside the <head> or <body> sections.
The script will operate as though it were situated exactly at the location of the <script> element.
<script> tags cannot be present in external scripts.
External JavaScript Advantages
There are a few benefits to placing scripts in external files:
(1).It keeps HTML and code apart.
(2).It facilitates reading and maintaining HTML and JavaScript.
(3).Page loads can be sped up with cached JavaScript files.
To include multiple script files on a single page, using multiple script tags:
Example
External References
There are three ways to reference an external script:
- Using the complete URL (web address)
- Using a file path (such as /js/),
- Without a way
This example links to myScript.js using the complete URL:
Example
This example uses a file path to link to myScript.js:
Example
This example uses no path to link to myScript.js:
Example