Careeroza
The script Element
Adding JavaScript
JavaScript makes pages interactive. It is added with <script>, either inline or from a file:
<!-- inline -->
<script>
console.log('Hello from the page');
</script>
<!-- external file (recommended) -->
<script src="app.js" defer></script>Example
Example
Click the button: the script changes the text of the paragraph:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<p id="demo">JavaScript can change HTML content.</p>
<button type="button" id="btn">Click me</button>
<script>
document.getElementById('btn').addEventListener('click', function () {
document.getElementById('demo').textContent = 'Hello JavaScript! ' + new Date().toLocaleTimeString();
});
</script>
</body>
</html>Result
defer and async
| Attribute | Download | Runs | Use for |
|---|---|---|---|
| (none) | blocks HTML parsing | immediately | avoid in the head |
defer | in parallel | after the HTML is parsed, in order | your own scripts (recommended) |
async | in parallel | as soon as it arrives, any order | independent scripts like analytics |
type="module" | in parallel | deferred by default | modern ES module code |