Contents
HTML script: Main Tips
- HTML
<script>
tags are used to reference or embed a code to execute. - Usually, a JavaScript code is used. However, HTML
<script>
can be used with other coding languages (e.g., GLSL – OpenGL Shading Language). - You must use both opening and closing tags.
- The global attributes are supported.
How to Use JavaScript in HTML
If you include the <script>
tags, HTML code will embed a JS script or reference an external file containing a script:
<script>
document.getElementById("learn").innerHTML = "It works!";
</script>
You can include the type
attribute to specify the media type of the given script:
<script type="application/javascript">
document.getElementById("p").innerHTML = "It works!";
</script>
Embedding an External Script
To include a JS script kept in an external file instead of embedding it directly, you need to define the source for the file using the src
attribute:
The document containing the script must have a .js extension. If it cannot be loaded (e.g., due to an incompatible type), an error will be sent. If all goes well, a load event will fire.
Note: if you try to both embed a JS script directly and specify an external file, only the latter one will be used.
Controlling the Loading Time for the Script
Beginners are traditionally told the <script>
tags belong in the head section of the document. However, as the browser starts fetching the script as soon as it encounters the element, this may slow down the loading time in some cases. To avoid this, you can place your script at the very end of the document, just before you close the <body> tags.
If you decide to keep the <script>
tags in the head section of the document, there are two attributes that can help you control the timing of loading the script. Both of them are of a boolean type and only work when you're adding an external file.
async
specifies that the script is executed without blocking parsing:
<script async>
document.getElementById("p").innerHTML = "It works!";
</script>
defer
specifies that the script is executed after parsing:
<script defer>
document.getElementById("p").innerHTML = "It works!";
</script>
If neither one of these two attributes is set, the script is executed before the browser continues parsing.
Note: neither async nor defer will work with a directly embedded script.
Deprecated Attributes
There are two attributes that were used with HTML <script>
tags previously, but have since been deprecated:
charset
specified character encoding in the externally linked script file.language
specified the scripting language.