Lesson goal: Connect a JavaScript File and Run Your First Program.
In this lesson, you will learn how to connect a JavaScript file and build the first version of your student profile project.
Open index.html and enter the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Student Profile | NHPlearning</title>
<link rel="stylesheet" href="style.css">
<script src="script.js" defer></script>
</head>
<body>
<main>
<h1>Student Profile</h1>
<p>Name: Aman Singh</p>
<p>Course: JavaScript Basics</p>
<p>Learning goal: Build useful websites.</p>
</main>
</body>
</html>
Look closely at these key parts:
<script src="script.js" defer></script>
src indicates the location of the JavaScript file. Since script.js is in the same directory as index.html, the filename alone suffices. The use of the defer attribute lets the browser complete loading the HTML before running this external script.
Next, open script.js and enter the following code:
console.log("Welcome, Aman Singh!");
console.log("Your JavaScript learning journey starts today.");
Make sure to write only JavaScript within script.js. Avoid including <script> tags inside the JavaScript file; these tags are only used in HTML.
Locate index.html in your project folder and open it using Chrome.
For this simple project, opening the HTML file directly is sufficient. However, for later lessons that involve data requests or modules, you will need to use a local development server.
Now, you should see the following:
Student Profile
Name: Aman Singh
Course: JavaScript Basics
Learning goal: Build useful websites.
style.css has not been applied yet.Open the Console for this page and then refresh it.
You should see the following expected messages:
Welcome, Aman Singh!
Your JavaScript learning journey starts today.
To modify your program, add this line to script.js:
console.log("Today I connected my first JavaScript file.");
You should now see the newly added message displayed.
To personalize your project, replace “Aman Singh” with your name in both the HTML and JavaScript files.
Additionally, add a console message that describes one project you are excited to build.
In summary, HTML connects your JavaScript file through a <script> element. After you edit and save your files, refresh the page to see the updated results from the JavaScript.