Тег SCRIPT

HTML Tag

The HTML tag declares client-side script (JavaScript) in an HTML document. When defining a client-side script the script tag is used for image manipulation, form validation, and dynamic changes of content. The tag can include either the script itself or a link to an external file containing scripts.The path to the external file is specified with src attribute.

script tag example

Syntax

The ) tags.

Important notes

There are a few ways an external script can be executed:

  • The async="async" attribute indicates, that the scripts are executed asynchronously, simultaneously with the loading of the page.
  • When there is no async and defer="defer" , the script is executed after the loading of the page.
  • If there is no async and defer, the script is executed before the loading of the page.

For selecting an HTML element, JavaScript uses the document.getElementById() method.

Example of HTML tag:

html> html> head> title>Title of the document title> head> body> p id="example"> p> script> document.getElementById("example").innerHTML = "My first JavaScript code"; script> body> html>

Differences Between HTML 4.01 and HTML5

HTML 4 requires the type attribute, whereas it is optional in HTML5. In HTML5, the async attribute is a new one. HTML5 does not support the HTML 4.01 xml:space attribute.

Differences Between HTML and XHTML

In XHTML, the content inside scripts is declared as #PCDATA (instead of CDATA). In such cases, the entities will be parsed.

In XHTML, all special characters must be encoded, or all the content must be wrapped inside a CDATA section.

Attributes

Attribute Value Description
async async Defines that the script is executed asynchronously. (For external scripts only).
Not supported in IE9 and older versions.
charset charset Defines character encoding, used in an external file with the JavaScript code.
defer defer Defines, that the script must be executed after the loading of the page. (For external scripts only).
src URL Defines the URL of an external file with the JavaScript code. (Can be defined either relative, or an absolute URL).
type media_type Defines the MIME-type of the script.

Источник

HTML Tag

The tag is used to embed a client-side script (JavaScript).

The element either contains scripting statements, or it points to an external script file through the src attribute.

Common uses for JavaScript are image manipulation, form validation, and dynamic changes of content.

Tips and Notes

Tip: If you want to learn more about JavaScript, visit our JavaScript Tutorial.

Browser Support

Attributes

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

Differences Between HTML and XHTML

In XHTML, the content inside scripts is declared as #PCDATA (instead of CDATA), which means that entities will be parsed.

This means that in XHTML, all special characters should be encoded, or all content should be wrapped inside a CDATA section:

Источник

In-depth Look Into The JavaScript Script Tag Attributes

The script tag is the primary method to insert JavaScript into HTML. The script tag was created by Netscape and was first implemented in Netscape Navigator 2, as far as the history of JavaScript is concerned. There are two ways you can use the script tag to insert JavaScript in HTML.

Inline JavaScript

You can insert JavaScript directly into an HTML file. Here is an example of how you would do that using the script tag.

 function helloWorld()  console.log('Hello World'); >; helloWord();  

I will go ahead and start with the script tag. Between the script tag, I will create a helloWorld function that prints the text “Hello World” to the console. On the next line, I will go ahead and invoke the function. This is the simplest way to include JavaScript in your HTML page but not the optimal way of doing it. This approach is good for short scripts or scripts which are page-specific. One more thing you need to remember about inline JavaScript is that it cannot be loaded asynchronously or deferred. Inline JavaScript is hence render-blocking; this means that the browser will parse and execute inline JavaScript from top to bottom before moving to the next line of code. Hence, it’s always better to include the inline JavaScripts (if any) in the page's footer once your HTML and CSS have loaded.

External JavaScript File

Another way to insert JavaScript into your HTML files is by using an external file. This is the most commonly used method to insert JavaScript files into HTML. Let’s have a look at an example. Assuming this is how files are organized in my project, where I have the index.html file and the main.js file, all in the same project folder.

This is how we can insert the main.js file into the index.html file. First, I will declare the script tag, and then in the script tag, we will include an attribute called src . The src attribute points to the JavaScript file that we want to include. It’s as simple as that; the main.js file is now included in our HTML.

Script Tag Attributes

There is often much confusion between the attributes of the script tag. The confusion is especially centered around two attributes, defer and async. But let’s look at all the script tag attributes one by one and understand how they impact how the browser treats the external JavaScript file.

type (optional)

The type attribute indicates the content type, also known as the MIME type, of the scripting language used in the external file you include in your HTML. This is how you would include a type attribute in your script tag.

 src = "main.js" type = "text/javascript" >  src = "main.js" type = "application/javascript" >  src = "main.js" type = "application/ecmascript" > 

Traditionally, the default type has always been "text/javascript" although this has been deprecated now but is still used by many developers. the current default is "application/javascript" or "application/ecmascript" . The safest option is to use these default options; else, using a different MIME type that is not supported by the browser ends up in the script being completely ignored by the browser.

crossorigin (optional)

Web pages often make requests to load resources on other servers. Here is where Cross-Origin Resource Sharing, often abbreviated as CORS, comes in. A cross-origin request is requested for a resource (e.g., style sheets, iframes, images, fonts, or scripts) from another domain. CORS is used to manage cross-origin requests. It defines a way of how a browser and server can interact to determine whether it is safe to allow the cross-origin request. CORS allows servers to specify who can access the assets on the server, among many other things. Here is an example of how you can use the crossorigin attribute.

 src = "main.js" crossorigin = "anonymous" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" >  src = "main.js" crossorigin = "use-credentials" > 

So there are two possible options for the crossorigin attribute. The first one being the "anonymous" option. In this case, a cross-origin request is performed, and no credentials are sent. This is often used with the integrity attribute, which sends a hash, and the receiving server verifies the request. We will look into this in detail as the next attribute. The next possible value for the crossorigin attribute is "use-credentials" . In this case, a cross-origin request is performed, and credentials can be sent along with the request. The credentials can be a cookie, a certificate, an HTTP Basic authentication, etc. Most of the time, you would be using the "anonymous" option, but it’s always good to know that an option to send the credentials exists as well.

integrity (optional)

The integrity attribute allows a browser to check the fetched script to ensure that the code is never loaded if the source has been manipulated. I’ll pull an example of the Bootstrap CDN code we often use to insert into our HTML.

  src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"> 

If you look at this code closely, it uses a crossorigin of "anonymous" and then there is this integrity attribute, which has something known as the SRI hash, where SRI stands for Subresource Integrity. Subresource Integrity (SRI) is a W3C specification that allows web developers to ensure that resources hosted on third-party servers have not been altered. So this means that the Bootstrap JavaScript being served on your page is as it was uploaded by the Bootstrap team and has not been altered. Use of SRI is highly recommended whenever you are using CORS.

async (optional)

To use the async attribute, all you need to do is include the attribute in the script tag. Please note that the async attribute works only for external JavaScript files and not for inline JavaScript.

The async attribute indicates the browser that the script should start downloading immediately and should not block the rest of the page's rendering. The JavaScript, however, is executed asynchronously with the rest of the page. The async method does not wait for the rest of the DOM to complete loading before it is executed. This is a non-render blocking way of loading your JavaScript.

defer (optional)

Using the defer attribute is as simple as using the async attribute. All you need to do is include the defer attribute in your script tag.

When using the defer attribute, the script execution is deferred until after all the document contents have been loaded completely. However, the script starts downloading immediately but is not executed until all the contents have been loaded and are ready.

What Happens If You Neither Include async Nor defer

In case you neither include the async or the defer attribute in your script, your script becomes render-blocking. This means the browser will first parse and execute the script before it moves to the next lines of code in your HTML. This impacts the loading speed of your web page. Get Access To More Such Stories on Cloudaffle
Thanks for reading, and hopefully, this was helpful!
I have created an extensive JavaScript cheatsheet. It has been in a manner where it becomes easy for you to refer to each property and method for various JavaScript objects. It’s absolutely free to download from the above link ☺.

Источник

Script tag attributes html

Тег предназначен для описания скриптов, может содержать ссылку на программу или ее текст на определенном языке. Скрипты могут располагаться во внешнем файле и связываться с любым HTML-документом. Такой подход позволяет использовать одни и те же общие функции на многих веб-страницах и ускоряет их загрузку, т.к. внешний файл кэшируется при первой загрузке, и скрипт вызывается быстрее при последующих вызовах.

может располагаться в заголовке или теле HTML-документа в неограниченном количестве. В большинстве случаев местоположение скрипта никак не сказывается на работу программы. Однако скрипты, которые должны выполняться в первую очередь, обычно помещают в заголовок документа.

Синтаксис

Атрибуты

async Загружает скрипт асинхронно. defer Откладывает выполнение скрипта до тех пор, пока вся страница не будет загружена полностью. language Устанавливает язык программирования на котором написан скрипт. src Адрес скрипта из внешнего файла для импорта в текущий документ. type Определяет тип содержимого тега .

Закрывающий тег

         

Результат данного примера показан на рис. 1.

Результат работы скрипта

Рис. 1. Результат работы скрипта

В данном примере с помощью скрипта выводится таблица, состоящая из пяти строк и столбцов, которая заполняется числами.

     function popup()   

Примечание

В HTML5 атрибут type можно опустить, он является необязательным и принимает значение text/javascript , если не указан явно. В предыдущих версиях HTML атрибут type необходим.

Статьи по теме

Источник

Читайте также:  Пояснение работы парсера
Оцените статью