In this post we will learn in details about the script tag. Many of use it but don’t know what difference and features in makes in HTML5. After reading this post you will be very familier with placing your script tags in the right way.
Let’s see the attributes of script tag
type attribute of script tag
We need to assign it to the MIME of the scripting language.
src attribute of script tag
It not necessary to write scripts inside the HTML document. We can create a external script file and link to the current document using src attribute. It can be assigned to a absolute or relative URL of the script file.
var b = 19;
charset attribute of script tag
Used along with src attribute. This is used to specify the character encoding of our external script file. The character encoding of our external file can also be specified in the HTTP Content-Type header’s charset directive of the external file. If src attribute and charset directive are missing then browser defaults to ISO-8859-1.
If both are specified the src is given higher priority. Its similar to the way HTML character encoding overrides the charset directive specified in HTTP response.
charset tells the browser how to interpret the file.
Browser executes the whole HTML document in a single thread called as main thread. So when browser encounters script tag it executes(downloads and executes if external file) the code inside it before continuing execution of HTML document. If browser encounters functions like setInterval, setTimeout or Web workers inside the script then it creates multiple threads which run alongside the main thread.
This behaviour is called synchronous or blocking. But async attribute can make it asynchronous if we are using external file. When browser encounters async attribute it creates a new thread and then downloads and executes the script in the newly created thread. So the HTML document execution is not blocked.
In the below example we are not using async attribute. Therefore the text “Hello World!!!!!” is never displayed.
In this below example we are using async attribute. Therefore while loops runs in a separate thread. We will be able to see the text “Hello World!!!!!”.
async is only recognised by HTML5. Remember to use it only for external script files.
Normally its set to false but when we create script tags dynamically, async attribute is set to true. Therefore dynamically created script tags run in separate threads. We can make it to false if we want, in that case the main thread is responsible for executing it.
defer attribute of script tag
If we assign defer attribute to a script tag then the code is executed after the complete HTML document is loaded and parsed. Its downloaded in a blocking manner. Its use is same as window.onload event. This attribute is only valid for external scripts.
This is all about script tag. Its not difficult to use script tag but understanding how it works is important to build a proper application. Thanks for reading.