JavaScript in HTML
// updated 2025-05-13 16:18
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:
1<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:
1<html>
2 <head>
3 <title>a page</title>
4 </head>
5 <body>
6 <h1>a page</h1>
7 <script>
8 // our script here - this is a basic true/false variable:
9 const aVariable = true
10 </script>
11 </body>
12</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:
1/* app.js */
2const aVariable = trueThen, we would load the file by placing it in a <script> tag:
1
2<html>
3 <head>
4 <title>a page</title>
5 </head>
6 <body>
7 <h1>a page</h1>
8 <script src="app.js"></script>
9 </body>
10</html>This makes for a more modular approach. We could then even add files from other sources like such:
1<html>
2 <head>
3 <title>a page</title>
4 </head>
5 <body>
6 <h1>a page</h1>
7 <script src="thirdpartycode1/app.js"></script>
8 <script src="thirdpartycode2/app.js"></script>
9 <script src="app.js"></script>
10 </body>
11</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
thirdpartycode2depends onthirdpartycode1thirdpartycode1should appear higher up in the HTML
- if
- in older HTML, the
scripttag might have the optionaltypeattribute- 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!
1<html>
2
3 <head>
4 ...
5 <script src="deferred.js" defer></script>
6 ...
7 </head>
8
9 <body>
10
11 <!-- all the tags here get loaded before deferred.js takes effect -->
12
13 </body>
14
15</html>