By the end of this lesson, learners will:
Web browsers don’t magically know what JavaScript code to run. You need to embed your JavaScript into your HTML pages so that the browser knows:
This is done using the <script>
tag.
You place JavaScript directly inside an HTML tag’s attribute, such as onclick
, onmouseover
, etc.
<button onclick="alert('Button clicked!')">Click me</button>
JavaScript is written inside a <script>
tag within the HTML file — usually placed in the <head>
or before the closing </body>
.
<!DOCTYPE html>
<html>
<head>
<title>Internal JS</title>
</head>
<body>
<h1>Welcome to Codevisionz</h1>
<script>
console.log("Hello from internal JavaScript!");
alert("Page loaded successfully!");
</script>
</body>
</html>
JavaScript code is stored in a separate .js
file, and the HTML file links to it using the src
attribute of the <script>
tag.
HTML File (index.html):
<!DOCTYPE html>
<html>
<head>
<title>External JS</title>
</head>
<body>
<h1>External JavaScript Demo</h1>
<script src="script.js"></script>
</body>
</html>
JavaScript File (script.js):
console.log("Hello from script.js!");
alert("External JavaScript is working!");
<script>
<body>
(recommended):<body>
<!-- content here -->
<script src="script.js"></script>
</body>
<head>
with defer
:<head>
<script src="script.js" defer></script>
</head>
Method | Where | Use Case | Recommended? |
---|---|---|---|
Inline | Inside HTML tag | Tiny snippets | ❌ No |
Internal | Inside <script> tag | Small apps, testing | ⚠️ Sometimes |
External | In .js file linked via src | Real apps | ✅ Yes |
Create two files in the same folder:
index.html
<!DOCTYPE html>
<html>
<head>
<title>Practice Script</title>
</head>
<body>
<h1>Welcome!</h1>
<script src="main.js"></script>
</body>
</html>
main.js
alert("Hello from your external file!");
✅ Open the HTML file in your browser — you should see the alert!