There are two ways of linking a Javascript file in HTML.
How to Link Javascript file in HTML?
1. Inline Javascript in HTML File
Using inline javascript, you can write the javascript code in the HTML file. You need to write the HTML code in the <script></script> tag.
All you need to do is create an index.html in your VS Code and write the Javascript code in the script tag. In the below code, I have used the triple equality operator. You can read more about this in the next blog post.
And, you can write below the HTML code as I have written below using shift + ! (emmet abbreviation) to get the HTML boilerplate in vs code. So, always use this way to get started quickly.
Example:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <body> <p>Linking Javascript file in HTML</p> <script> let color = "red"; if(color === "red") alert("You have chosen red color"); </script> </body> </html>
Output:
2. Using External Javascript File
Now, I will use the same above code to show you how to Link Javascript file in HTML using external file.
First, you have to create a file and save it as .js file. Now, write a code in this javascript file and link it in the HTML using the below way.
<script src=”externalFile.js”></script>
You have to write the above code in an HTML file.
Example:
In the below image, You can see I have created two files.
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <body> <p>Linking Javascript file in HTML</p> <script src="externalFile.js"></script> </body> </html>
externalFile.js
let color = "red"; if (color === "red") alert("You have chosen red color");
In this method, we will get the same output as the first one.
But if you are working on a mid-size or big project then always use external javascript files.
Your tasks
- Create an Inline JS in HTML and display any random message to the console (not using alert).
- Create an external JS file and display any random message to the console.