JavaScript in HTML
Much like in CSS, we can include JavaScript in an HTML page in one of three ways:
- In-line script
<script>
tag (in CSS, we used the<style>
tag)- External script file (on a separate file with a .js extension)
In-line
As with CSS, we can place JavaScript inside the attribute values of HTML tags like this:
<a href="javascript:history.back()">Go back</a>
(This HTML would link to the last place that the user visited!)
Script tag
A more separated form of JavaScript would appear in a <script>
tag within an HTML file:
<html>
<head>
<title>a page</title>
</head>
<body>
<h1>a page</h1>
<script>
// our script here - this is a basic true/false variable:
const aVariable = true
</script>
</body>
</html>
Although this appears neater than in-line JavaScript, this still makes the code inside the <script>
tag usable only in this specific HTML file. We could not use this code on other HTML pages.
External script file
Even better then, we could place JavaScript in a file like this:
/* app.js */
const aVariable = true
Then, we would load the file by placing it in a <script>
tag:
<html>
<head>
<title>a page</title>
</head>
<body>
<h1>a page</h1>
<script src="app.js"></script>
</body>
</html>
This makes for a more modular approach. We could then even add files from other sources like such:
<html>
<head>
<title>a page</title>
</head>
<body>
<h1>a page</h1>
<script src="thirdpartycode1/app.js"></script>
<script src="thirdpartycode2/app.js"></script>
<script src="app.js"></script>
</body>
</html>
With this, we can re-use code more easily and reserve the HTML for page structure.
Note also:
- the order of the
<script>
tags matter:- if
thirdpartycode2
depends onthirdpartycode1
thirdpartycode1
should appear higher up in the HTML
- if
- in older HTML, the
script
tag might have the optionaltype
attribute- this has become optional as browsers now can detect languages better
Deferred file
If a <script>
tag somehow has to appear in the <head>
tag of an HTML document, we can use the defer
keyword. This will ensure that the rest of the HTML file gets loaded before the script's execution!
<html>
<head>
...
<script src="deferred.js" defer></script>
...
</head>
<body>
<!-- all the tags here get loaded before deferred.js takes effect -->
</body>
</html>