HTML Language Question: HTML script Tag Tutorial with Examples

Check HTML script Tag Tutorial with Examples from Learn HTML section on e akhabaar



HTML enclosing tag. The block inside these tags will be referred to as script body or block and may contain JavaScript, WebGL GLSL or reference to the external script files which can be server from the current domain or external domain. But in general script tag is used to run JavaScript code which is very popular even defacto scripting language for web pages.

Run Script Code

The script tag is used to run JavaScript code where the code will be put into the script tags. The given code will be executed immediately without waiting for a specific event. In the following example, we will show a message box with a message.


   
      

The HTML Script Tag Example

Set Script Type

Even there are multiple scripting languages that can be used with the script tag JavaScript is the default scripting language that is used with script implicitly. Alternatively, we can specify the scripting language with the type attribute of the script tag. In the following example, we will put two script block where first is JavaScript which value is text/javascript and the second block is WebGL which value is x-shader/x-vertex.


   
      

The HTML Script Tag Example

Specify External Script File

Script tag can also load and run an external script file. The script file can be on the same domain or on the other domain. The script file path or URI will be specified with the attribute src.


   
      

The HTML Script Tag Example

Run Script Asynchronized

By default, the specified script block of the script file is loaded as soon as possible. But in some cases using lazy loading can be more beneficial which is called asynchronized loading. This will iterate the loading of the script and will create less load for the web client or web browser. Lazy loading generally used with external script files and the attribute async is used. All the external script files will be loaded synchronized in the following example.


   
      

The HTML Script Tag Example

Set Character Set/Encoding For External Script

By default, the current HTML document character set or encoding is used for the script block. In some cases, the encoding of the script block especially external script files can be different than the current HTML document.


   
      

The HTML Script Tag Example

Execute Script After The Page Parsing

Even async provides lazy loading there is an alternative way to load external scripts that are called as defer attribute. With the defer attribute the given external script will be loaded after the page parsing which means after all the elements of the HTML document or web page are parsed and put properly. Defer attributes can be only used for the external script files.


   
      

The HTML Script Tag Example

Post your comments about HTML script Tag Tutorial with Examples below.