HTML <script> -tag
Voorbeeld
Schrijf "Hallo JavaScript!" met javascript:
<script>
document.getElementById("demo").innerHTML = "Hello JavaScript!";
</script>
Definitie en gebruik
De <script>
tag wordt gebruikt om een client-side script (JavaScript) in te sluiten.
Het <script>
element bevat ofwel scriptstatements, ofwel verwijst het naar een extern scriptbestand via het src-attribuut.
Veelvoorkomende toepassingen voor JavaScript zijn beeldmanipulatie, formuliervalidatie en dynamische wijzigingen van inhoud.
Tips en opmerkingen
Tip: Kijk ook naar het <noscript> element voor gebruikers die scripts in hun browser hebben uitgeschakeld, of een browser hebben die geen client-side scripting ondersteunt.
Tip: als je meer wilt weten over JavaScript, bezoek dan onze JavaScript-tutorial .
Browserondersteuning
Element | |||||
---|---|---|---|---|---|
<script> | Yes | Yes | Yes | Yes | Yes |
attributen
Attribute | Value | Description |
---|---|---|
async | async | Specifies that the script is downloaded in parallel to parsing the page, and executed as soon as it is available (before parsing completes) (only for external scripts) |
crossorigin | anonymous use-credentials |
Sets the mode of the request to an HTTP CORS Request |
defer | defer | Specifies that the script is downloaded in parallel to parsing the page, and executed after the page has finished parsing (only for external scripts) |
integrity | filehash | Allows a browser to check the fetched script to ensure that the code is never loaded if the source has been manipulated |
nomodule | True False |
Specifies that the script should not be executed in browsers supporting ES2015 modules |
referrerpolicy | no-referrer no-referrer-when-downgrade origin origin-when-cross-origin same-origin strict-origin strict-origin-when-cross-origin unsafe-url |
Specifies which referrer information to send when fetching a script |
src | URL | Specifies the URL of an external script file |
type | scripttype | Specifies the media type of the script |
Verschillen tussen HTML en XHTML
In XHTML wordt de inhoud in scripts gedeclareerd als #PCDATA (in plaats van CDATA), wat betekent dat entiteiten worden geparseerd.
Dit betekent dat in XHTML alle speciale tekens moeten worden gecodeerd, of dat alle inhoud in een CDATA-sectie moet worden verpakt:
<script type="text/javascript">
//<![CDATA[
var i = 10;
if (i < 5) {
// some code
}
//]]>
</script>
Algemene kenmerken
De <script>
tag ondersteunt ook de Global Attributes in HTML .
Gerelateerde pagina's
HTML-zelfstudie: HTML-scripts
HTML DOM-referentie: Script Object
JavaScript-zelfstudie: JavaScript leren
Standaard CSS-instellingen
De meeste browsers geven het <script>
element weer met de volgende standaardwaarden:
script {
display: none;
}