<script>
Embeds JavaScript code in the page or loads it from a file to give the page behavior.
- Display
- none
- Closing tag
- Required
- Permitted content
- JavaScript code or data, depending on
type. Withsrcthe element stays empty
Example
#<p>Lessons completed today: <strong id="count">0</strong></p>
<button type="button" id="done">Complete lesson</button>
<script>
const count = document.getElementById('count');
const button = document.getElementById('done');
button.addEventListener('click', () => {
count.textContent = Number(count.textContent) + 1;
});
</script>The script sits below the button, so by the time it runs, both elements already exist on the page.
Definition and usage
#The <script> element runs JavaScript. You can write the code directly between the tags or point to a file in the src attribute. In the latter case the element must stay empty, and any content written inside is ignored.
A regular script without extra attributes stops the page from being built: the parser waits until the code has been downloaded and run, and only then reads the rest of the HTML. That causes two typical problems: a script in the head delays showing the page, and the code can’t find elements that sit lower in the file, because they don’t exist yet. The solution is the defer attribute, the module type, or placing the script at the end of <body>.
The type attribute decides what the content is. Without it, it’s a regular script, module means a JavaScript module with import and export, and data types, e.g. application/json or application/ld+json, make the browser run nothing and only store the data for other scripts or search engines.
The closing </script> tag is required, even with src. The notation <script src="app.js" /> doesn’t work in HTML: the slash is ignored, and the browser treats the rest of the page as script code.
Syntax
#<script src="file.js" defer></script>
<script>
// JavaScript code
</script>Attributes
#URL
The address of a file with JavaScript code. The browser stores such a file in its cache and can reuse it on other subpages. Remember the closing tag, even when the element is empty.boolean attribute
Downloads the script in the background without holding up the parser, and runs it only after all the HTML has loaded, just before theDOMContentLoadedevent. Several scripts withdeferrun in the order in which they appear in the code. It works only together withsrc.boolean attribute
Downloads the script in the background and runs it as soon as it has downloaded, even if the page is still loading. The execution order isn’t guaranteed, soasyncsuits independent scripts, such as visit statistics, and not code that relies on other files. In regular scripts it works only together withsrc.none | module | importmap | data type
The kind of content. Omitted, it means regular JavaScript, so writingtype="text/javascript"is unnecessary.modulecreates a module,importmapdefines an import map for modules, and other values, e.g.application/ld+json, turn the element into a data block that the browser doesn’t execute.JavaScript module
Runs the code as a module: you can useimportandexportin it, it runs in strict mode, and its variables don’t leak into the global scope. Modules behave like scripts withdeferby default. They usually won’t work when you open an HTML file straight from disk (file://), so run the page through a local server.boolean attribute
A script with this attribute runs only in browsers that don’t know modules. It was used to deliver a fallback version for very old browsers. Today every popular browser supports modules, so you rarely need it.cryptographic hash, e.g. `sha384-…`
Subresource Integrity: the browser checks that the downloaded file has exactly the hash you gave. If the file has been changed, for example swapped on a CDN server, the script won’t run. For files from another domain thecrossoriginattribute is also required.crossorigin
anonymous | use-credentials
Fetches a script from another domain in CORS mode. It is required withintegrityfor files from external servers, and it also makes errors from such a script reachwindow.onerrorwith a full description rather than as a generic “Script error.”. The server must respond with the proper CORS header.
The element also supports all global attributes, such as class, id, style and hidden.
Attributes in practice
#src
URLThe address of a file with JavaScript code. The browser stores such a file in its cache and can reuse it on other subpages. Remember the closing tag, even when the element is empty.
<script src="/js/app.js"></script>defer
boolean attributeDownloads the script in the background without holding up the parser, and runs it only after all the HTML has loaded, just before the DOMContentLoaded event. Several scripts with defer run in the order in which they appear in the code. It works only together with src.
<head>
<script src="/js/menu.js" defer></script>
<script src="/js/app.js" defer></script>
</head>Both files download in parallel and run in order, first menu.js, then app.js, once the HTML is ready.
async
boolean attributeDownloads the script in the background and runs it as soon as it has downloaded, even if the page is still loading. The execution order isn’t guaranteed, so async suits independent scripts, such as visit statistics, and not code that relies on other files. In regular scripts it works only together with src.
<script src="/js/analytics.js" async></script>type
none | module | importmap | data typeThe kind of content. Omitted, it means regular JavaScript, so writing type="text/javascript" is unnecessary. module creates a module, importmap defines an import map for modules, and other values, e.g. application/ld+json, turn the element into a data block that the browser doesn’t execute.
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "Course",
"name": "HTML and CSS Course from the Basics",
"description": "24 lessons with exercises and a live preview.",
"provider": {
"@type": "Organization",
"name": "CodeWorlds"
}
}
</script>This kind of structured data helps search engines understand what is on the page.
type="module"
JavaScript moduleRuns the code as a module: you can use import and export in it, it runs in strict mode, and its variables don’t leak into the global scope. Modules behave like scripts with defer by default. They usually won’t work when you open an HTML file straight from disk (file://), so run the page through a local server.
<script type="module">
import { formatPrice } from './utils.js';
document.querySelector('#price').textContent = formatPrice(149);
</script>nomodule
boolean attributeA script with this attribute runs only in browsers that don’t know modules. It was used to deliver a fallback version for very old browsers. Today every popular browser supports modules, so you rarely need it.
<script type="module" src="/js/app.js"></script>
<script nomodule src="/js/app-legacy.js"></script>integrity
cryptographic hash, e.g. `sha384-…`Subresource Integrity: the browser checks that the downloaded file has exactly the hash you gave. If the file has been changed, for example swapped on a CDN server, the script won’t run. For files from another domain the crossorigin attribute is also required.
<script
src="/vendor/confetti.min.js"
integrity="sha384-X3AWfWhQFwjzp273ynuHHCFyQuYlir97rA86ZO0Oogpfx0Mj78VDdnJqUkzHUU+e"
defer
></script>You can generate a file’s hash in the terminal with the command openssl dgst -sha384 -binary file.js | openssl base64 -A. Many CDNs provide ready-made code with the hash.
More examples
#<script type="application/json" id="course">
{ "title": "Python Course", "lessons": 24 }
</script>
<p id="info">Loading…</p>
<script>
const course = JSON.parse(document.getElementById('course').textContent);
document.getElementById('info').textContent = course.title + ': ' + course.lessons + ' lessons';
</script>The first element has the type application/json, so the browser doesn’t run it. The second script reads the data from it and writes it into the paragraph.
Default CSS
#Most browsers display this element with these default styles:
script {
display: none;
}Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- Always close the element:
<script src="app.js"></script>. The self-closing form doesn’t work. - Mark scripts in
<head>withdeferortype="module". The page will show up faster, and the code will be sure to find all the elements. - Don’t put passwords or secret API keys in scripts that run in the browser. Anyone can view them in the page source.
Related entries
#- <noscript>Content the browser shows only when JavaScript is turned off.
- <head>The invisible part of the document holding metadata: the title, character encoding, description, styles, and scripts.
- <body>The visible part of the document: everything the user sees on the page and can interact with.
- <link>Connects the document to an external resource: a stylesheet, a page icon, a font, or another language version.
- <style>A CSS stylesheet written directly in the HTML document.
Practise it in lessons
#Spotted a mistake or missing an example? Write to us.