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

AttributeDownloadRunsUse for
(none)blocks HTML parsingimmediatelyavoid in the head
deferin parallelafter the HTML is parsed, in orderyour own scripts (recommended)
asyncin parallelas soon as it arrives, any orderindependent scripts like analytics
type="module"in paralleldeferred by defaultmodern ES module code