Starting from this lesson, we are going to move on to the more practical uses of JavaScript. To begin with, let's talk about how the language works in the frontend part of a web application.
Frontend is the part of the web application that is displayed to the user, meaning your JavaScript code will be embedded into the webpage, and it will run on top of the browser environment, instead of Node.js.
There are two ways to embed JavaScript code. You can either use in-page JavaScript like this:
1<!doctype html>
2<html lang="en">
3 <head>
4 <meta charset="UTF-8" />
5 <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6 <title>Document</title>
7 </head>
8
9 <body>
10 <p>Lorem ipsum dolor. . .</p>
11 <p>. . .</p>
12
13 <script>
14 // Your JavaScript code here
15 </script>
16 </body>
17</html>
Or put your JavaScript code in a separate file:
1.
2├── index.html
3└── index.js
And then import it into your HTML document.
1<!doctype html>
2<html lang="en">
3 <head>
4 <meta charset="UTF-8" />
5 <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6 <title>Document</title>
7 </head>
8
9 <body>
10 <button onclick="example()">Click Me</button>
11
12 <script src="index.js"></script>
13 </body>
14</html>
In most cases, the second method is recommended. As your project grows, putting everything in a single file will make future maintenance a nightmare.
The JavaScript file can be imported similar to how we can load images, except you must use the <script>
tag.