<script>: The Script element
HTML Элемент** <script>
**используется для встраивания или подключения исполняемого JavaScript кода. Элемент <script>
также может использоваться с другими языками, такими как GLSL (en-US) от WebGL.
Content categories | Метаданные, Потоковый контент, Фразовый контент. |
---|---|
Разрешённый контент | Динамический скрипт, используя атрибут text/javascript . |
Пропуск тегов | Нет. Открывающий и закрывающий теги обязательны |
Разрешённые родительские элементы | Любые элементы в которых разрешены метаданные или фразовый контент |
Разрешённая ARIA роль | Отсутствует |
DOM интерфейс | HTMLScriptElement |
Атрибуты
Этот элемент включает глобальные атрибуты.
async
HTML5-
Это логический атрибут, указывающий браузеру, если возможно, загружать скрипт, указанный в атрибуте
, асинхронно.src
Предупреждение: Атрибут
не будет оказывать никакого эффекта, если атрибутasync
отсутствует.Обычно браузеры загружаютsrc
<script>
синхронно, (т.е.async="false"
) во время разбора документа.Динамически вставленный<script>
(используя, например,document.createElement
) по умолчанию загружаются браузером асинхронно, поэтому для включения синхронной загрузки (т.е. когда скрипты загружаются в порядке их вставки) укажитеasync="false"
. crossorigin
-
Обычные элементы тега
script
передают мало информации вwindow.onerror
для скриптов, которые не проходят проверку CORS (en-US). Чтобы разрешить ведение журнала ошибок сайта, которые используют отдельный домен для статических файлов (например, изображение, видео-файл, CSS-стили или Javascript-код), используйте атрибут
. Посмотрите статью «настройки атрибутов CORS» для более наглядного объяснения его допустимых аргументов.crossorigin
defer
-
Это логический атрибут, указывающий браузеру, что скрипт должен выполняться после разбора документа, но до события
DOMContentLoaded (en-US)
.Скрипты с атрибутом
будут предотвращать запуск событияdefer
DOMContentLoaded (en-US)
до тех пор, пока скрипт не загрузится полностью и не завершится его инициализация. integrity
-
This attribute contains inline metadata that a user agent can use to verify that a fetched resource has been delivered free of unexpected manipulation. See Subresource Integrity (en-US).
nomodule
-
This Boolean attribute is set to indicate that the script should not be executed in browsers that supportES2015 modules — in effect, this can be used to serve fallback scripts to older browsers that do not support modular JavaScript code.
nonce
-
A cryptographic nonce (number used once) to whitelist inline scripts in a script-src Content-Security-Policy (en-US). The server must generate a unique nonce value each time it transmits a policy. It is critical to provide a nonce that cannot be guessed as bypassing a resource's policy is otherwise trivial.
src
-
This attribute specifies the URI of an external script; this can be used as an alternative to embedding a script directly within a document.
Предупреждение: Если у элемента
script
будет указан атрибут
, то он не должен иметь встроенный скрипт между тегами.src
text
-
Like the
textContent
attribute, this attribute sets the text content of the element. Unlike thetextContent
attribute, however, this attribute is evaluated as executable code after the node is inserted into the DOM. type
-
Этот атрибут указывает тип представленного скрипта. Значение этого атрибута будет находиться в одной из следующих категорий:
- Omitted or a JavaScript MIME type: For HTML5-compliant browsers this indicates the script is JavaScript. HTML5 specification urges authors to omit the attribute rather than provide a redundant MIME type. In earlier browsers, this identified the scripting language of the embedded or imported (via the
src
attribute) code. JavaScript MIME types are listed in the specification. module
: For HTML5-compliant browsers the code is treated as a JavaScript module. The processing of the script contents is not affected by thecharset
and
attributes. For information on usingdefer
module
, see ES6 in Depth: Modules. Code may behave differently when themodule
keyword is used.- Any other value: The embedded content is treated as a data block which won't be processed by the browser. Developers must use a valid MIME type that is not a JavaScript MIME type to denote data blocks. The
src
attribute will be ignored.**Примечание:**in Firefox you could specify the version of JavaScript contained in a
<script>
element by including a non-standardversion
parameter inside thetype
attribute — for exampletype="text/javascript;version=1.8"
. This has been removed in Firefox 59 (see баг 1428745).
- Omitted or a JavaScript MIME type: For HTML5-compliant browsers this indicates the script is JavaScript. HTML5 specification urges authors to omit the attribute rather than provide a redundant MIME type. In earlier browsers, this identified the scripting language of the embedded or imported (via the
Устаревшие атрибуты
charset
Deprecated-
If present, its value must be an ASCII case-insensitive match for "
utf-8
". Both it’s unnecessary to specify thecharset
attribute, because documents must use UTF-8, and thescript
element inherits its character encoding from the document. language
Deprecated-
Like the
type
attribute, this attribute identifies the scripting language in use. Unlike thetype
attribute, however, this attribute’s possible values were never standardized. Thetype
attribute should be used instead.
Примечания
Элемент <script>
без указания атрибутов async
, defer
или type="module"
, а также встроенный скрипт, загружается и выполняется сразу, до того как браузер продолжит разбор документа.
Для обработки скрипт должен иметь тип данных text/javascript
, но браузеры снисходительны и блокируют обработку только в том случае, если скрипт представляет данные одного из типов: изображение (image/*
); видео (video/*
); аудио (audio/*
); или text/csv
. Если скрипт заблокирован, элементу отправляется событие error (en-US)
, если не было отправлено событие load (en-US)
.
Примеры
Основное использование
Эти примеры показывают как импортировать скрипт используя элемент <script>
в HTML4 и HTML5.
<!-- HTML4 -->
<script type="text/javascript" src="javascript.js"></script>
<!-- HTML5 -->
<script src="javascript.js"></script>
Module fallback
Браузеры, поддерживающие использование значения module
для атрибута type
, игнорируют любые скрипты с атрибутом nomodule
. Это разрешает использовать модульные скрипты, и в тот же самый момент позволяет использовать nomodule-
скрипты для браузеров без поддержки модульных скриптов.
<script type="module" src="main.mjs"></script>
<script nomodule src="fallback.js"></script>
Спецификация
Specification |
---|
HTML Standard # the-script-element |
Совместимость браузеров
BCD tables only load in the browser
Примечания по совместимости
In older browsers that don't support the async
attribute, parser-inserted scripts block the parser; script-inserted scripts execute asynchronously in IE and WebKit, but synchronously in Opera and pre-4 Firefox. In Firefox 4, the async
DOM property defaults to true
for script-created scripts, so the default behaviour matches the behaviour of IE and WebKit.
To request script-inserted external scripts be executed in the insertion order in browsers where the document.createElement("script").async
evaluates to true
(such as Firefox 4), set async=false
on the scripts you want to maintain order.
Предупреждение: Never call document.write()
from an async script. In Firefox 3.6, calling document.write()
has an unpredictable effect. In Firefox 4, calling document.write()
from an async script has no effect (other than printing a warning to the error console).