HTML and the JavaScript Tag
The <script> tag embeds or links JavaScript code within an HTML page, either inline between the tags or via the src attribute pointing to an external file.
Scripts are commonly placed at the end of <body>, or loaded with the defer attribute in <head>, so they don't block the page from rendering while downloading.
<script src="file.js" defer></script>Inline vs external scripts
Inline scripts are written directly between <script> tags. External scripts use src="file.js" and are cacheable and reusable across pages.
Loading behavior
The defer attribute delays script execution until after the HTML is parsed, without blocking rendering, and is recommended for most scripts placed in the head.
<script>
alert('Hello from JavaScript!');
</script>(shows an alert box: Hello from JavaScript!)Inline JavaScript runs immediately when the browser reaches this tag.
<head>
<script src="app.js" defer></script>
</head>(app.js runs after HTML parsing completes)defer lets the browser download the script early but run it after parsing.
Key points
- <script> embeds or links JavaScript code.
- src attribute loads an external .js file.
- defer runs scripts after HTML parsing without blocking rendering.
- Scripts placed at the end of <body> also avoid blocking render.
