aboutsummaryrefslogtreecommitdiff
path: root/files/uk/web/html/елемент/script/index.html
blob: 10b6e5096dd7896e984048745cd57990f1f2a3af (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
---
title: '<script>: Елементи тега Script'
slug: Web/HTML/Елемент/script
translation_of: Web/HTML/Element/script
---
<div>{{HTMLRef}}</div>

<p><span class="seoSummary"><strong>HTML <code>&lt;script&gt;</code> </strong>елемент використовується для вбудовування або посилання виконавчого коду; зазвичай використовується для вбудовування або посилання на код JavaScript.</span> Тег <code>&lt;script&gt; може</code> бути використаний для других мов програмування, такі як <a href="/en-US/docs/Web/API/WebGL_API">WebGL</a>'s GLSL та мов для створення шейдерів.</p>

<table class="properties">
 <tbody>
  <tr>
   <th scope="row">Категорія вмісту</th>
   <td><a href="/uk/docs/https://wiki.developer.mozilla.org/en-US/docs/Web/Guide/HTML/Content_categories#Metadata_content">Мета дата</a>, <a href="/uk/docs/https://wiki.developer.mozilla.org/en-US/docs/Web/Guide/HTML/Content_categories#Flow_content">Плаваючий контент</a>, <a href="/uk/docs/https://wiki.developer.mozilla.org/en-US/docs/Web/Guide/HTML/Content_categories#Phrasing_content">Зміст фразування</a>.</td>
  </tr>
  <tr>
   <th scope="row">Дозволений вміст</th>
   <td>Динамічний сценарій, такий як text/javascript.</td>
  </tr>
  <tr>
   <th scope="row">Опущення тегів</th>
   <td>{{no_tag_omission}}</td>
  </tr>
  <tr>
   <th scope="row">Дозволені батьки</th>
   <td>Будь-який елемент, який приймає вміст <a href="/uk/docs/https://wiki.developer.mozilla.org/en-US/docs/Web/Guide/HTML/Content_categories#Metadata_content">метаданих</a>, або будь-який елемент, який приймає <a href="/uk/docs/https://wiki.developer.mozilla.org/en-US/docs/Web/Guide/HTML/Content_categories#Phrasing_content">вміст фраз</a>.</td>
  </tr>
  <tr>
   <th scope="row">Дозволені ролі ARIA</th>
   <td>Немае</td>
  </tr>
  <tr>
   <th scope="row">DOM-інтерфейс</th>
   <td>{{domxref("HTMLScriptElement")}}</td>
  </tr>
 </tbody>
</table>

<h2 id="Attributes">Attributes</h2>

<p>Цей елемент включає <a href="/uk/docs/https://wiki.developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes">глобальні атрибути</a>.</p>

<dl>
 <dt>{{htmlattrdef("async")}}{{HTMLVersionInline(5)}}</dt>
 <dd>
 <p>This is a Boolean attribute indicating that the browser should, if possible, load the script asynchronously and then execute it as soon as it’s downloaded.</p>

 <div class="warning">
 <p>This attribute must not be used if the <code>src</code> attribute is absent (i.e. for inline scripts). If it is included in this case it will have no effect.</p>
 </div>

 <p>Browsers usually assume the worst case scenario and load scripts synchronously, (i.e. <code>async="false"</code>) during HTML parsing.</p>

 <p>Dynamically inserted scripts (using {{domxref("document.createElement()")}}) load asynchronously by default, so to turn on synchronous loading (i.e. scripts load in the order they were inserted) set <code>async="false"</code>.</p>

 <p>This attribute allows the elimination of <strong>render-blocking JavaScript</strong> where the page would have to load and execute scripts before finishing to render the page. <code>defer</code> has a similar effect in this case.</p>

 <p>See {{anch("Browser compatibility")}} for notes on browser support. See also <a href="/en-US/docs/Games/Techniques/Async_scripts">Async scripts for asm.js</a>.</p>
 </dd>
 <dt>{{htmlattrdef("crossorigin")}}</dt>
 <dd>Normal <code>script</code> elements pass minimal information to the {{domxref('GlobalEventHandlers.onerror', 'window.onerror')}} for scripts which do not pass the standard {{Glossary("CORS")}} checks. To allow error logging for sites which use a separate domain for static media, use this attribute. See <a href="/en-US/docs/Web/HTML/CORS_settings_attributes">CORS settings attributes</a> for a more descriptive explanation of its valid arguments.</dd>
 <dt>{{htmlattrdef("defer")}}</dt>
 <dd>
 <p>This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed, but before firing {{event("DOMContentLoaded")}}.</p>

 <p>Scripts with the <code>defer</code> attribute will prevent the <code>DOMContentLoaded</code> event from firing until the script has loaded and finished evaluating.</p>

 <div class="warning">
 <p>This attribute must not be used if the <code>src</code> attribute is absent (i.e. for inline scripts), in this case it would have no effect.</p>
 </div>

 <p>To achieve a similar effect for dynamically inserted scripts use <code>async="false"</code> instead. Scripts with the <code>defer</code> attribute will execute in the order in which they appear in the document.</p>

 <p>This attribute allows the elimination of <strong>render-blocking JavaScript</strong> where the page would have to load and execute scripts before finishing to render the page. <code>async</code> has a similar effect in this case.</p>
 </dd>
 <dt>{{htmlattrdef("integrity")}}</dt>
 <dd>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 <a href="/en-US/docs/Web/Security/Subresource_Integrity">Subresource Integrity</a>.</dd>
 <dt>{{htmlattrdef("nomodule")}}</dt>
 <dd>This Boolean attribute is set to indicate that the script should not be executed in browsers that support<a href="https://hacks.mozilla.org/2015/08/es6-in-depth-modules/"> ES2015 modules</a> — in effect, this can be used to serve fallback scripts to older browsers that do not support modular JavaScript code.</dd>
 <dt>{{htmlattrdef("nonce")}}</dt>
 <dd>A cryptographic nonce (number used once) to whitelist inline scripts in a <a href="/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src">script-src Content-Security-Policy</a>. 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.</dd>
 <dt id="attr-referrer">{{htmlattrdef("referrerpolicy")}}</dt>
 <dd>Indicates which <a href="/en-US/docs/Web/API/Document/referrer">referrer</a> to send when fetching the script, or resources fetched by the script:
 <ul>
  <li><code>no-referrer</code>: The {{HTTPHeader("Referer")}} header will not be sent.</li>
  <li><code>no-referrer-when-downgrade</code> (default): The {{HTTPHeader("Referer")}} header will not be sent to {{Glossary("origin")}}s without {{Glossary("TLS")}} ({{Glossary("HTTPS")}}).</li>
  <li><code>origin</code>: The sent referrer will be limited to the origin of the referring page: its <a href="/en-US/docs/Archive/Mozilla/URIScheme">scheme</a>, {{Glossary("host")}}, and {{Glossary("port")}}.</li>
  <li><code>origin-when-cross-origin</code>: The referrer sent to other origins will be limited to the scheme, the host, and the port. Navigations on the same origin will still include the path.</li>
  <li><code>same-origin</code>: A referrer will be sent for {{Glossary("Same-origin policy", "same origin")}}, but cross-origin requests will contain no referrer information.</li>
  <li><code>strict-origin</code>: Only send the origin of the document as the referrer when the protocol security level stays the same (e.g. HTTPS→HTTPS), but don't send it to a less secure destination (e.g. HTTPS→HTTP).</li>
  <li><code>strict-origin-when-cross-origin</code>: Send a full URL when performing a same-origin request, but only send the origin when the protocol security level stays the same (e.g.HTTPS→HTTPS), and send no header to a less secure destination (e.g. HTTPS→HTTP).</li>
  <li><code>unsafe-url</code>: The referrer will include the origin <em>and</em> the path (but not the <a href="/en-US/docs/Web/API/HTMLHyperlinkElementUtils/hash">fragment</a>, <a href="/en-US/docs/Web/API/HTMLHyperlinkElementUtils/password">password</a>, or <a href="/en-US/docs/Web/API/HTMLHyperlinkElementUtils/username">username</a>). <strong>This value is unsafe</strong>, because it leaks origins and paths from TLS-protected resources to insecure origins.</li>
 </ul>

 <div class="blockIndicator note">
 <p><strong>Note</strong>: An empty string value (<code>""</code>) is both the default value, and a fallback value if <code>referrerpolicy</code> is not supported. If <code>referrerpolicy</code> is not explicitly specified on the <code>&lt;script&gt;</code> element, it will adopt a higher-level referrer policy, i.e. one set on the whole document or domain. If a higher-level policy is not available, the empty string is treated as being equivalent to <code>no-referrer-when-downgrade</code>.</p>
 </div>
 </dd>
 <dt>{{htmlattrdef("src")}}</dt>
 <dd>
 <p>This attribute specifies the <abbr>URI</abbr> of an external script; this can be used as an alternative to embedding a script directly within a document.</p>

 <div class="warning">
 <p>If a <code>script</code> element has a <code>src</code> attribute specified, it should not have a script embedded inside its tags since it can lead to unexpected behavior. The unexpected behavior is because it is only the JavaScript in the file referenced in the <code>src</code> attribute that will be added to the HTML page.</p>
 </div>
 </dd>
 <dt>{{htmlattrdef("type")}}</dt>
 <dd>
 <p>This attribute indicates the type of script represented. The value of this attribute will be in one of the following categories:</p>

 <ul>
  <li><strong>Omitted or a JavaScript MIME type:</strong> This indicates the script is JavaScript. The 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 <code>src</code> attribute) code. JavaScript MIME types are <a href="/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types#JavaScript_types">listed in the specification</a>.</li>
  <li><strong><code>module</code>:</strong> Causes the code to be treated as a JavaScript module. The processing of the script contents is not affected by the <code>charset</code> and <code>defer</code> attributes. For information on using <code>module</code>, see our <a href="/en-US/docs/Web/JavaScript/Guide/Modules">JavaScript modules</a> guide.</li>
  <li><strong>Any other value:</strong> 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 <code>src</code> attribute will be ignored.</li>
 </ul>

 <div class="note">
 <p><strong>Note: </strong>in Firefox you could specify the version of JavaScript contained in a <code>&lt;script&gt;</code> element by including a non-standard <code>version</code> parameter inside the <code>type</code> attribute — for example <code>type="text/javascript;version=1.8"</code>. This has been removed in Firefox 59 (see {{bug(1428745)}}).</p>
 </div>
 </dd>
</dl>

<h3 id="Deprecated_attributes">Deprecated attributes</h3>

<dl>
 <dt>{{htmlattrdef("charset")}} {{Deprecated_inline}}</dt>
 <dd>If present, its value must be an ASCII case-insensitive match for "<code>utf-8</code>". It’s unnecessary to specify the <code>charset</code> attribute, because documents must use UTF-8, and the <code>script</code> element inherits its character encoding from the document.</dd>
 <dt>{{htmlattrdef("language")}} {{Deprecated_inline}}</dt>
 <dd>Like the <code>type</code> attribute, this attribute identifies the scripting language in use. Unlike the <code>type</code> attribute, however, this attribute’s possible values were never standardized. The <code>type</code> attribute should be used instead.</dd>
</dl>

<h2 id="Notes">Notes</h2>

<p>Scripts without {{HTMLAttrxRef("async", "script")}} , {{HTMLAttrxRef("defer", "script")}} or <code>type="module"</code> attributes, as well as inline scripts, are fetched and executed immediately, before the browser continues to parse the page.</p>

<p>The script should be served with the <code>text/javascript</code> MIME type, but browsers are lenient and only block them if the script is served with an image type (<code>image/*</code>); a video type (<code>video/*</code>); an audio (<code>audio/*</code>) type; or <code>text/csv</code>. If the script is blocked, an {{event("error")}} is sent to the element, if not a {{event("load")}} event is sent.</p>

<h2 id="Examples">Examples</h2>

<h3 id="Basic_usage">Basic usage</h3>

<p>These examples show how to import (an external) script using the <code>&lt;script&gt;</code> element in both HTML4 and HTML5:</p>

<pre class="brush: html">&lt;!-- HTML4 --&gt;
&lt;script type="text/javascript" src="javascript.js"&gt;&lt;/script&gt;

&lt;!-- HTML5 --&gt;
&lt;script src="javascript.js"&gt;&lt;/script&gt;
</pre>

<p>And the following examples show how to put (an inline) script inside the <code>&lt;script&gt;</code> element in both HTML4 and HTML5:</p>

<pre class="brush: html">&lt;!-- HTML4 --&gt;
&lt;script type="text/javascript"&gt;
  alert("Hello World!");
&lt;/script&gt;

&lt;!-- HTML5 --&gt;
&lt;script&gt;
  alert("Hello World!");
&lt;/script&gt;</pre>

<h3 id="Module_fallback">Module fallback</h3>

<p>Browsers that support the <code>module</code> value for the <code>type</code> attribute ignore any script with a <code>nomodule</code> attribute. That enables you to use module scripts while also providing <code>nomodule</code>-marked fallback scripts for non-supporting browsers.</p>

<pre class="brush: html">&lt;script type="module" src="main.js"&gt;&lt;/script&gt;
&lt;script nomodule src="fallback.js"&gt;&lt;/script&gt;</pre>

<h2 id="Specifications">Specifications</h2>

<table class="standard-table">
 <thead>
  <tr>
   <th scope="col">Specification</th>
   <th scope="col">Status</th>
   <th scope="col">Comments</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>{{SpecName("HTML WHATWG", "scripting.html#the-script-element", "&lt;script&gt;")}}</td>
   <td>{{Spec2("HTML WHATWG")}}</td>
   <td>Removed the {{HTMLAttrxRef("charset", "script")}} attribute</td>
  </tr>
  <tr>
   <td>{{SpecName("HTML5.3", "semantics-scripting.html#the-script-element", "&lt;script&gt;")}}</td>
   <td>{{Spec2("HTML5.3")}}</td>
   <td>Removed the {{HTMLAttrxRef("charset", "script")}} attribute</td>
  </tr>
  <tr>
   <td>{{SpecName("HTML5.2", "semantics-scripting.html#the-script-element", "&lt;script&gt;")}}</td>
   <td>{{Spec2("HTML5.2")}}</td>
   <td>Adds the <code>module</code> {{HTMLAttrxRef("type", "script")}}</td>
  </tr>
  <tr>
   <td>{{SpecName("HTML5.1", "semantics-scripting.html#the-script-element", "&lt;script&gt;")}}</td>
   <td>{{Spec2("HTML5.1")}}</td>
   <td></td>
  </tr>
  <tr>
   <td>{{SpecName("HTML5 W3C", "scripting-1.html#script", "&lt;script&gt;")}}</td>
   <td>{{Spec2("HTML5 W3C")}}</td>
   <td></td>
  </tr>
  <tr>
   <td>{{SpecName("HTML4.01", "interact/scripts.html#h-18.2.1", "&lt;script&gt;")}}</td>
   <td>{{Spec2("HTML4.01")}}</td>
   <td></td>
  </tr>
  <tr>
   <td>{{SpecName("Subresource Integrity", "#htmlscriptelement", "&lt;script&gt;")}}</td>
   <td>{{Spec2("Subresource Integrity")}}</td>
   <td>Adds the {{HTMLAttrxRef("integrity", "script")}} attribute.</td>
  </tr>
 </tbody>
</table>

<h2 id="Browser_compatibility">Browser compatibility</h2>



<div>{{Compat("html.elements.script", 2)}}</div>

<h3 id="Compatibility_notes">Compatibility notes</h3>

<p>In older browsers that don't support the <code>async</code> 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 <code>async</code> DOM property defaults to <code>true</code> for script-created scripts, so the default behaviour matches the behaviour of IE and WebKit.</p>

<p>To request script-inserted external scripts be executed in the insertion order in browsers where the <code>document.createElement("script").async</code> evaluates to <code>true</code> (such as Firefox 4), set <code>async="false"</code> on the scripts you want to maintain order.</p>

<div class="warning">
<p>Never call <code>document.write()</code> from an async script. In Firefox 3.6, calling <code>document.write()</code> has an unpredictable effect. In Firefox 4, calling <code>document.write()</code> from an async script has no effect (other than printing a warning to the error console).</p>
</div>

<h2 id="See_also">See also</h2>

<ul>
 <li>{{domxref("document.currentScript")}}</li>
 <li><a href="https://pie.gd/test/script-link-events/">Ryan Grove's &lt;script&gt; and &lt;link&gt; node event compatibility chart</a></li>
 <li><a href="https://flaviocopes.com/javascript-async-defer/">Flavio Copes' article on loading JavaScript efficiently and explaining the differences between <code>async</code> and <code>defer</code></a></li>
 <li><code><a href="https://bytutorial.com/tutorials/javascript">Javascript tips and tricks</a>.</code></li>
 <li><a href="/en-US/docs/Web/JavaScript/Guide/Modules">JavaScript modules</a> guide</li>
</ul>