What is the script HTML element?

About

A client-side script is a program that is:

  • linked (server-side script)
  • or directly embedded in an HTML document (in-line script)

Scripts in HTML have “run-to-completion” semantics, meaning that the browser will generally run the script uninterrupted before doing anything else, such as firing further events or continuing to parse the document.

Definition

The script may be defined:

If the src attribute is not set, user agents must interpret the contents of the element as the script. If the src has a URI value, user agents must ignore the element's contents and retrieve the script via the URI.

Using external files generally produces faster pages because the JavaScript and CSS files are cached by the browser. JavaScript and CSS that are inlined in HTML documents get downloaded every time the HTML document is requested.

GUI / Background

Interface

An interface script is a script that respond to clicks or other user interactions.

Background

see HTML - Web Worker. Background script

Element

The SCRIPT element 1) 2) 3) places a script within a document. This element may appear any number of times in the HEAD or BODY of an HTML document.

Syntax:

<script
  type="ContentType"
  src="URI"
  async=false
  defer=false >
</script>
<!-- The below script tag is then illegal and will not work -->
<script />

where:

  • ContentType is the mime that defines the script language (by default text/javascript)
  • URI can point to an external file
  • Asynchronous Load (for more information between async vs defer, see the dedicated page: What is the difference between the Async and Defer Script attribute ?)
    • async=false or true to execute script in parallel (ie the user agent can continue parsing and rendering and run the script as soon as possible.
    • defer=false or true indicates no document creation (ie no “document.write” in javascript) - the user agent can continue parsing and rendering and executes the script after.
  • integrity is a hash digest to control that the script was not tempered during the transport
  • crossorigin is a cors attribute

it's non-conforming to have executable script in a script element when the src attribute is present.

The fallback element is the noscript element.

With the template element, they are script-supporting elements. They are used to support scripts.

Example:

  • src
<script src="http://example.com/PathToMyScript.js" type="application/javascript"></script>

Including a script tag cause the browser to stop the rendering process of the page. It will wait for the script to load, execute, and then continue. This is generally bad and why you should always include scripts at the bottom of the page.

Type

The type attribute of the script element defines the language such as

  • text/javascript default (ie javascript)
  • text/tcl
  • text/vbscript

See language

Integrity

To calculate the integrity, see HTML - Integrity attribute (SRI | Source Resource Integrity)

Execution

The program executes on the client's machine when:

  • the document loads,
  • or at some other time such as when an event occurs.

Load / Fetch

The default fetch mode for scripts that appear within a SCRIPT element is to :

This is bad for performance. You should always use one of this option:

Load Event

Scripts are executed and the load event is executed.

onLoad HTML attribute

With the onLoad HTML attribute

function onBowserLoad() {
    const browser = bowser.getParser(window.navigator.userAgent);
    console.log(`The bowser script has loaded and executed. You can then use it. Your browser name is "${browser.getBrowserName()}"`);
}
<script 
   type="application/javascript" 
   src="https://cdnjs.cloudflare.com/ajax/libs/bowser/2.11.0/bundled.min.js" 
   integrity="sha512-hsF/cpBvi/vjCP4Ps/MrPUFk6l4BqcGbzVUhqjJdX2SmAri1Oj8FBUGCvBiKHYd6gg3vLsV16CtIRNOvK5X4lQ==" 
   crossorigin="anonymous"
   referrerpolicy="no-referrer"
   onLoad="onBowserLoad(event)"
   defer>
</script>

Load event in Javascript alone

In Javascript with dynamic javascript loading:

var script      = document.createElement('script');
script.src      = "https://cdnjs.cloudflare.com/ajax/libs/bowser/2.11.0/bundled.min.js"; // Set the location of the script
script.integrity ="sha512-hsF/cpBvi/vjCP4Ps/MrPUFk6l4BqcGbzVUhqjJdX2SmAri1Oj8FBUGCvBiKHYd6gg3vLsV16CtIRNOvK5X4lQ==";
script.crossOrigin="anonymous";
script.referrerPolicy="no-referrer";
let head = document.querySelector('head');
head.appendChild( script );
script.addEventListener('load', function() {
    const browser = bowser.getParser(window.navigator.userAgent);
    console.log(`The bowser script has loaded and executed. You can then use it. Your browser name is "${browser.getBrowserName()}"`);
});

Type

A script can be run:

  • immediately (default)
  • or in parallel

The flow of execution stay the same: when an algorithm B says to return to another algorithm A, it implies that A called B. Upon returning to A, the implementation must continue from where it left off in calling B.

Immediately

An operation that is to run immediately must interrupt the currently running task, run itself, and then resume the previously running task.

Parallel

In parallel, the currently running task is not interrupted, ie the subsequent steps are run, one after another, at the same time as other logic in the specification (e.g., at the same time as the event loop).

To run a script in parallel, you can use one of the resource fetch instruction such as the async attribute of the script element.

In parallel - Doc ref

Language

Declaration

HTML's support for scripts is independent of the scripting language. Scripts are evaluated by script engines that must be known to a user agent (The browser generally).

As HTML does not rely on a specific scripting language, document authors must explicitly tell user agents the language of each script.

This may be done either through:

  • a default declaration
  • or a local declaration.

Default

For all scripts in a document with the following META declaration in the HEAD:

Syntax:

<META http-equiv="Content-Script-Type" content="type">

where type defines the type of the scripting language

In the absence of a META declaration, the default can be set by a Content-Script-Type HTTP header.

Local

The value of the type attribute for a SCRIPT element overrides the default scripting language for that element.

Example of document with TCL as default language and the call of a vbsscript

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<HTML>
<HEAD>
<TITLE>A document with SCRIPT</TITLE>
<META http-equiv="Content-Script-Type" content="text/tcl">
<SCRIPT type="text/vbscript" src="http://someplace.com/progs/vbcalc">
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
...some JavaScript...
</SCRIPT>
</BODY>
</HTML>

Example

JavaScript

 
<INPUT NAME="num" onchange="if (!checkNum(this.value, 1, 10)) {this.focus();this.select();} else {thanks()}"  VALUE="0">
<SCRIPT type="text/javascript">
...
</SCRIPT>

See Javascript - Script

VBScript

vbs script

Event handler for a text field:

<INPUT name="edit1" size="50">    
<SCRIPT type="text/vbscript">
    Sub edit1_changed()
      If edit1.value = "abc" Then
        button1.enabled = True
      Else
        button1.enabled = False
      End If
    End Sub
</SCRIPT>

Tcl

Same example than above but in TCL

<INPUT name="edit1" size="50">
<SCRIPT type="text/tcl">
  proc edit1_changed {} {
     if {[edit value] == abc} {
       button1 enable 1
     } else {
       button1 enable 0
     }
   }
   edit1 onChange edit1_changed
</SCRIPT>

HTML Element Script Reference

How

Scripts should refer to an element according to its assigned name.

Precedence

Scripting engines should observe the following precedence rules when identifying an element:

Management

Get (DOM Accessors)

The document attribute document.scripts return an HTMLCollection of the script elements in the Document.

State processing

A script element has several associated pieces of state.

How to load a script dynamically?

How to load a script dynamically with Javascript?

Documentation / Reference





Discover More
Java Conceptuel Diagram
A page with snippets of thymeleaf Java template engine

HTML, Text or any other thymelaf snippet
Header Bidding Expert On Weather
Advertising - Header Bidding (Advance or Pre-bidding)

Header bidding is a mediation that consists of an auction that takes place (by default outside) of the ad server via the header of a web page. When the page loads, the header script loads before anything...
Browser - DOM Web Api

The DOM Web API is a part of the Web Api that implements the DOM API in the browser to manipulate the DOM representation of a Web Page. This API made possible to manipulate programmatically Web Page (in...
Browser
Browser - Javascript

javascript script in the browser Javascript code can be executed via the script html tag via the eval function that evaluates a string as javascript ...
Browser
Browser - Render blocking resources

All resources that are before the DomContentLoaded event are blocking the construction of the DOM. They are therefore known as render blocking resources They all have a render...
DOM - Load event (onload, load listener)

The load event is an event that is fired / emitted on: an HTML element that fetch resources on the browser window when the page has finish loading. This event is a timing page load event To...
Devtool Chrome Event Listener
Event - Missed Event

Parsing of HTML files happens synchronously and incrementally, meaning that the parser can pause at any point to let scripts run. It does mean that authors need to be careful to avoid hooking event handlers...
HTML - (Document) Parser

HTML documents consist of a tree of elements and text. The specification defines a set of elements that can be used in HTML, along with rules. If a document is transmitted with the text/html mime type,...
HTML - (Flow|Body) Content

Most elements that are used in the body of documents and applications are categorized as flow content. Flow content consists of flow elements intermixed with normal character data. (ifbodhead...
HTML - Body element

HTML The body element represents the body of a document (as opposed to the document’s metadata). The document property document.body returns the body element. Can be set, to replace the body element....



Share this page:
Follow us:
Task Runner