aboutsummaryrefslogtreecommitdiff
path: root/files/uk/web/api/html_dom_api
diff options
context:
space:
mode:
authorPeter Bengtsson <mail@peterbe.com>2020-12-08 14:43:23 -0500
committerPeter Bengtsson <mail@peterbe.com>2020-12-08 14:43:23 -0500
commit218934fa2ed1c702a6d3923d2aa2cc6b43c48684 (patch)
treea9ef8ac1e1b8fe4207b6d64d3841bfb8990b6fd0 /files/uk/web/api/html_dom_api
parent074785cea106179cb3305637055ab0a009ca74f2 (diff)
downloadtranslated-content-218934fa2ed1c702a6d3923d2aa2cc6b43c48684.tar.gz
translated-content-218934fa2ed1c702a6d3923d2aa2cc6b43c48684.tar.bz2
translated-content-218934fa2ed1c702a6d3923d2aa2cc6b43c48684.zip
initial commit
Diffstat (limited to 'files/uk/web/api/html_dom_api')
-rw-r--r--files/uk/web/api/html_dom_api/index.html472
-rw-r--r--files/uk/web/api/html_dom_api/microtask_guide/index.html324
2 files changed, 796 insertions, 0 deletions
diff --git a/files/uk/web/api/html_dom_api/index.html b/files/uk/web/api/html_dom_api/index.html
new file mode 100644
index 0000000000..4f94294e96
--- /dev/null
+++ b/files/uk/web/api/html_dom_api/index.html
@@ -0,0 +1,472 @@
+---
+title: The HTML DOM API
+slug: Web/API/HTML_DOM_API
+tags:
+ - API
+ - Beginner
+ - DOM
+ - Documents
+ - Elements
+ - HTML DOM
+ - HTML DOM API
+ - NeedsTranslation
+ - Nodes
+ - Overview
+ - TopicStub
+ - Web
+ - Windows
+ - hierarchy
+translation_of: Web/API/HTML_DOM_API
+---
+<p>{{DefaultAPISidebar("HTML DOM")}}</p>
+
+<p>The <strong>HTML DOM API</strong> is made up of the interfaces that define the functionality of each of the {{Glossary("element", "elements")}} in {{Glossary("HTML")}}, as well as any supporting types and interfaces they rely upon.</p>
+
+<p>The functional areas included in the HTML DOM API include:</p>
+
+<ul>
+ <li>Access to and control of HTML elements via the {{Glossary("DOM")}}.</li>
+ <li>Access to and manipulation of form data.</li>
+ <li>Interacting with the contents of 2D images and the context of an HTML {{HTMLElement("canvas")}}, for example to draw on top of them.</li>
+ <li>Management of media connected to the HTML media elements ({{HTMLElement("audio")}} and {{HTMLElement("video")}}).</li>
+ <li>Dragging and dropping of content on webpages.</li>
+ <li>Access to the browser navigation history</li>
+ <li>Supporting and connective interfaces for other APIs such as <a href="/en-US/docs/Web/Web_Components">Web Components</a>, <a href="/en-US/docs/Web/API/Web_Storage_API">Web Storage</a>, <a href="/en-US/docs/Web/API/Web_Workers_API">Web Workers</a>, <a href="/en-US/docs/Web/API/WebSockets_API">WebSocket</a>, and <a href="/en-US/docs/Web/API/Server-sent_events">Server-sent events</a>.</li>
+</ul>
+
+<h2 id="HTML_DOM_concepts_and_usage">HTML DOM concepts and usage</h2>
+
+<p>In this article, we'll focus on the parts of the HTML DOM that involve engaging with HTML elements. Discussion of other areas, such as <a href="/en-US/docs/Web/API/HTML_Drag_and_Drop_API">Drag and Drop</a>, <a href="/en-US/docs/Web/API/WebSockets_API">WebSockets</a>, <a href="/en-US/docs/Web/API/Web_Storage_API">Web Storage</a>, etc. can be found in the documentation for those APIs.</p>
+
+<h3 id="Structure_of_an_HTML_document">Structure of an HTML document</h3>
+
+<p>The Document Object Model ({{Glossary("DOM")}}) is an architecture that describes the structure of a {{domxref("document")}}; each document is represented by an instance of the interface {{domxref("Document")}}. A document, in turn, consists of a hierarchical tree of <strong>nodes</strong>, in which a node is a fundamental record representing a single object within the document (such as an element or text node).</p>
+
+<p>Nodes may be strictly organizational, providing a means for grouping other nodes together or for providing a point at which a hierarchy can be constructed; other nodes may represent visible components of a document. Each node is based on the {{domxref("Node")}} interface, which provides properties for getting information about the node as well as methods for creating, deleting, and organizing nodes within the DOM.</p>
+
+<p>Nodes don't have any concept of including the content that is actually displayed in the document. They're empty vessels. The fundamental notion of a node that can represent visual content is introduced by the {{domxref("Element")}} interface. An <code>Element</code> object instance represents a single element in a document created using either HTML or an {{glossary("XML")}} vocabulary such as {{glossary("SVG")}}.</p>
+
+<p>For example, consider a document with two elements, one of which has two more elements nested inside it:</p>
+
+<p><img alt="Structure of a document with elements inside a document in a window" src="https://mdn.mozillademos.org/files/16587/dom-structure.svg" style="display: block; height: 379px; margin: 0 auto; width: 291px;"></p>
+
+<p>While the {{domxref("Document")}} interface is defined as part of the <a href="/en-US/docs/Web/API/Document_Object_Model">DOM</a> specification, the HTML specification significantly enhances it to add information specific to using the DOM in the context of a web browser, as well as to using it to represent HTML documents specifically.</p>
+
+<p>Among the things added to <code>Document</code> by the HTML standard are:</p>
+
+<ul>
+ <li>Support for accessing various information provided by the {{Glossary("HTTP")}} headers when loading the page, such as the <a href="/en-US/docs/Web/API/Document/location">location</a> from which the document was loaded, <a href="/en-US/docs/Web/API/Document/cookie">cookies</a>, <a href="/en-US/docs/Web/API/Document/lastModified">modification date</a>, <a href="/en-US/docs/Web/API/Document/referrer">referring site</a>, and so forth.</li>
+ <li>Access to lists of elements in the document's {{HTMLElement("head")}} block and <a href="/en-US/docs/Web/API/Document/body">body</a>, as well as lists of the <a href="/en-US/docs/Web/API/Document/images">images</a>, <a href="/en-US/docs/Web/API/Document/links">links</a>, <a href="/en-US/docs/Web/API/Document/scripts">scripts</a>, etc. contained in the document.</li>
+ <li>Support for interacting with the user by examining <a href="/en-US/docs/Web/API/Document/hasFocus">focus</a> and by executing commands on <a href="/en-US/docs/Web/HTML/Global_attributes/contenteditable">editable content</a>.</li>
+ <li>Event handlers for document <a href="/en-US/docs/Web/API/GlobalEventHandlers">events defined by the HTML standard</a> to allow access to <a href="/en-US/docs/Web/API/MouseEvent">mouse</a> and <a href="/en-US/docs/Web/API/KeyboardEvent">keyboard</a> events, <a href="/en-US/docs/Web/API/HTML_Drag_and_Drop_API">drag and drop</a>, <a href="/en-US/docs/Web/API/HTMLMediaElement">media control</a>, and more.</li>
+ <li>Event handlers for events that can be delivered to both elements and documents; these presently include only <a href="/en-US/docs/Web/API/HTMLElement/oncopy">copy</a>, <a href="/en-US/docs/Web/API/HTMLElement/oncut">cut</a>, and <a href="/en-US/docs/Web/API/HTMLElement/onpaste">paste</a> actions.</li>
+</ul>
+
+<h3 id="HTML_element_interfaces">HTML element interfaces</h3>
+
+<p>The <code>Element</code> interface has been further adapted to represent HTML elements specifically by introducing the {{domxref("HTMLElement")}} interface, which all more specific HTML element classes inherit from. This expands the <code>Element</code> class to add HTML-specific general features to the element nodes. Properties added by <code>HTMLElement</code> include for example {{domxref("HTMLElement.hidden", "hidden")}} and {{domxref("HTMLElement.innerText", "innerText")}}. <code>HTMLElement</code> also adds all the <a href="/en-US/docs/Web/API/GlobalEventHandlers">global event handlers</a>.</p>
+
+<p>An {{Glossary("HTML")}} document is a DOM tree in which each of the nodes is an HTML element, represented by the {{domxref("HTMLElement")}} interface. The <code>HTMLElement</code> class, in turn, implements <code>Node</code>, so every element is also a node (but not the other way around). This way, the structural features implemented by the {{domxref("Node")}} interface are also available to HTML elements, allowing them to be nested within each other, created and deleted, moved around, and so forth.</p>
+
+<p>The <code>HTMLElement</code> interface is generic, however, providing only the functionality common to all HTML elements such as the element's ID, its coordinates, the HTML making up the element, information about scroll position, and so forth.</p>
+
+<p>In order to expand upon the functionality of the core <code>HTMLElement</code> interface to provide the features needed by a specific element, the <code>HTMLElement</code> class is subclassed to add the needed properties and methods. For example, the {{HTMLElement("canvas")}} element is represented by an object of type {{domxref("HTMLCanvasElement")}}. <code>HTMLCanvasElement</code> augments the <code>HTMLElement</code> type by adding properties such as {{domxref("HTMLCanvasElement.height", "height")}} and methods like {{domxref("HTMLCanvasElement.getContext", "getContext()")}} to provide canvas-specific features.</p>
+
+<p>The overall inheritance for HTML element classes looks like this:</p>
+
+<p><img alt="Hierarchy of interfaces for HTML elements" src="https://mdn.mozillademos.org/files/16596/html-dom-hierarchy.svg" style="display: block; height: 565px; margin: 0 auto; width: 661px;"></p>
+
+<p>As such, an element inherits the properties and methods of all of its ancestors. For example, consider a {{HTMLElement("a")}} element, which is represented in the DOM by an object of type {{domxref("HTMLAnchorElement")}}. The element, then, includes the anchor-specific properties and methods described in that class's documentation, but also those defined by {{domxref("HTMLElement")}} and {{domxref("Element")}}, as well as from {{domxref("Node")}} and, finally, {{domxref("EventTarget")}}.</p>
+
+<p>Each level defines a key aspect of the utility of the element. From <code>Node</code>, the element inherits concepts surrounding the ability for the element to be contained by another element, and to contain other elements itself. Of special importance is what is gained by inheriting from <code>EventTarget</code>: the ability to receive and handle events such as mouse clicks, play and pause events, and so forth.</p>
+
+<p>There are elements that share commonalities and thus have an additional intermediary type. For example, the {{HTMLElement("audio")}} and {{HTMLElement("video")}} elements both present audiovisual media. The corresponding types, {{domxref("HTMLAudioElement")}} and {{domxref("HTMLVideoElement")}}, are both based upon the common type {{domxref("HTMLMediaElement")}}, which in turn is based upon {{domxref("HTMLElement")}} and so forth. <code>HTMLMediaElement</code> defines the methods and properties held in common between audio and video elements.</p>
+
+<p>These element-specific interfaces make up the majority of the HTML DOM API, and are the focus of this article. To learn more about the actual structure of the <a href="/en-US/docs/Web/API/Document_Object_Model">DOM</a>, see <a href="/en-US/docs/Web/API/Document_Object_Model/Introduction">Introduction to the DOM</a>.</p>
+
+<h2 id="HTML_DOM_target_audience">HTML DOM target audience</h2>
+
+<p>The features exposed by the HTML DOM are among the most commonly-used APIs in the web developer's arsenal. All but the most simple web applications will use some features of the HTML DOM.</p>
+
+<h2 id="HTML_DOM_API_interfaces">HTML DOM API interfaces</h2>
+
+<p>The majority of the interfaces that comprise the HTML DOM API map almost one-to-one to individual HTML elements, or to a small group of elements with similar functionality. In addition, the HTML DOM API includes a few interfaces and types to support the HTML element interfaces.</p>
+
+<h3 id="HTML_element_interfaces_2">HTML element interfaces</h3>
+
+<p>These interfaces represent specific HTML elements (or sets of related elements which have the same properties and methods associated with them).</p>
+
+<div class="index">
+<ul>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLAnchorElement"><code>HTMLAnchorElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLAreaElement"><code>HTMLAreaElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLAudioElement"><code>HTMLAudioElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLBRElement"><code>HTMLBRElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLBaseElement"><code>HTMLBaseElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLBaseFontElement"><code>HTMLBaseFontElement</code></a> {{obsolete_inline}}</span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLBodyElement"><code>HTMLBodyElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLButtonElement"><code>HTMLButtonElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLCanvasElement"><code>HTMLCanvasElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLDListElement"><code>HTMLDListElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLDataElement"><code>HTMLDataElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLDataListElement"><code>HTMLDataListElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLDetailsElement"><code>HTMLDetailsElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLDialogElement"><code>HTMLDialogElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLDirectoryElement"><code>HTMLDirectoryElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLDivElement"><code>HTMLDivElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLElement"><code>HTMLElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLEmbedElement"><code>HTMLEmbedElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLFieldSetElement"><code>HTMLFieldSetElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLFontElement"><code>HTMLFontElement</code></a> {{obsolete_inline}}</span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLFormElement"><code>HTMLFormElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLFrameElement"><code>HTMLFrameElement</code></a> {{obsolete_inline}}</span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLFrameSetElement"><code>HTMLFrameSetElement</code></a> {{obsolete_inline}}</span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLHRElement"><code>HTMLHRElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLHeadElement"><code>HTMLHeadElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLHeadingElement"><code>HTMLHeadingElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLHtmlElement"><code>HTMLHtmlElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLIFrameElement"><code>HTMLIFrameElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLImageElement"><code>HTMLImageElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLInputElement"><code>HTMLInputElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLIsIndexElement"><code>HTMLIsIndexElement</code></a> {{obsolete_inline}}</span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLLIElement"><code>HTMLLIElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLLabelElement"><code>HTMLLabelElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLLegendElement"><code>HTMLLegendElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLLinkElement"><code>HTMLLinkElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLMapElement"><code>HTMLMapElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLMarqueeElement"><code>HTMLMarqueeElement</code></a> {{deprecated_inline}}</span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLMediaElement"><code>HTMLMediaElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLMenuElement"><code>HTMLMenuElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLMenuItemElement"><code>HTMLMenuItemElement</code></a> {{obsolete_inline}}</span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLMetaElement"><code>HTMLMetaElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLMeterElement"><code>HTMLMeterElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLModElement"><code>HTMLModElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLOListElement"><code>HTMLOListElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLObjectElement"><code>HTMLObjectElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLOptGroupElement"><code>HTMLOptGroupElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLOptionElement"><code>HTMLOptionElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLOutputElement"><code>HTMLOutputElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLParagraphElement"><code>HTMLParagraphElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLParamElement"><code>HTMLParamElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLPictureElement"><code>HTMLPictureElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLPreElement"><code>HTMLPreElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLProgressElement"><code>HTMLProgressElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLQuoteElement"><code>HTMLQuoteElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLScriptElement"><code>HTMLScriptElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLSelectElement"><code>HTMLSelectElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLSlotElement"><code>HTMLSlotElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLSourceElement"><code>HTMLSourceElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLSpanElement"><code>HTMLSpanElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLStyleElement"><code>HTMLStyleElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLTableCaptionElement"><code>HTMLTableCaptionElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLTableCellElement"><code>HTMLTableCellElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLTableColElement"><code>HTMLTableColElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLTableElement"><code>HTMLTableElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLTableRowElement"><code>HTMLTableRowElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLTableSectionElement"><code>HTMLTableSectionElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLTemplateElement"><code>HTMLTemplateElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLTextAreaElement"><code>HTMLTextAreaElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLTimeElement"><code>HTMLTimeElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLTitleElement"><code>HTMLTitleElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLTrackElement"><code>HTMLTrackElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLUListElement"><code>HTMLUListElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLUnknownElement"><code>HTMLUnknownElement</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLVideoElement"><code>HTMLVideoElement</code></a></span></span></li>
+</ul>
+</div>
+
+<h3 id="Web_app_and_browser_integration_interfaces">Web app and browser integration interfaces</h3>
+
+<p>These interfaces offer access to the browser window and document that contain the HTML, as well as to the browser's state, available plugins (if any), and various configuration options.</p>
+
+<div class="index">
+<ul>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/ApplicationCache"><code>ApplicationCache</code></a> {{obsolete_inline}}</span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/BarProp"><code>BarProp</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/External"><code>External</code></a> {{deprecated_inline}}</span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/Navigator"><code>Navigator</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/Plugin"><code>Plugin</code></a> {{obsolete_inline}}</span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/PluginArray"><code>PluginArray</code></a> {{obsolete_inline}}</span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><code><a href="/en-US/docs/Web/API/Window">Window</a></code></span></span></li>
+</ul>
+</div>
+
+<h3 id="Form_support_interfaces">Form support interfaces</h3>
+
+<p>These interfaces provide structure and functionality required by the elements used to create and manage forms, including the {{HTMLElement("form")}} and {{HTMLElement("input")}} elements.</p>
+
+<div class="index">
+<ul>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/FormDataEvent"><code>FormDataEvent</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLFormControlsCollection"><code>HTMLFormControlsCollection</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLOptionsCollection"><code>HTMLOptionsCollection</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/RadioNodeList"><code>RadioNodeList</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/ValidityState"><code>ValidityState</code></a></span></span></li>
+</ul>
+</div>
+
+<h3 id="Canvas_and_image_interfaces">Canvas and image interfaces</h3>
+
+<p>These interfaces represent objects used by the Canvas API as well as the {{HTMLElement("img")}} element and {{HTMLElement("picture")}} elements.</p>
+
+<div class="index">
+<ul>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/CanvasGradient"><code>CanvasGradient</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/CanvasPattern"><code>CanvasPattern</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/CanvasRenderingContext2D"><code>CanvasRenderingContext2D</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/ImageBitmap"><code>ImageBitmap</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/ImageBitmapRenderingContext"><code>ImageBitmapRenderingContext</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/ImageData"><code>ImageData</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/OffscreenCanvas"><code>OffscreenCanvas</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/OffscreenCanvasRenderingContext2D"><code>OffscreenCanvasRenderingContext2D</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/Path2D"><code>Path2D</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/TextMetrics"><code>TextMetrics</code></a></span></span></li>
+</ul>
+</div>
+
+<h3 id="Media_interfaces">Media interfaces</h3>
+
+<p>The media interfaces provide HTML access to the contents of the media elements: {{HTMLElement("audio")}} and {{HTMLElement("video")}}.</p>
+
+<div class="index">
+<ul>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/AudioTrack"><code>AudioTrack</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/AudioTrackList"><code>AudioTrackList</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/MediaError"><code>MediaError</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/TextTrack"><code>TextTrack</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/TextTrackCue"><code>TextTrackCue</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/TextTrackCueList"><code>TextTrackCueList</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/TextTrackList"><code>TextTrackList</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/TimeRanges"><code>TimeRanges</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/TrackEvent"><code>TrackEvent</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/VideoTrack"><code>VideoTrack</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/VideoTrackList"><code>VideoTrackList</code></a></span></span></li>
+</ul>
+</div>
+
+<h3 id="Drag_and_drop_interfaces">Drag and drop interfaces</h3>
+
+<p>These interfaces are used by the <a href="/en-US/docs/Web/API/HTML_Drag_and_Drop_API">HTML Drag and Drop API</a> to represent individual draggable (or dragged) items, groups of dragged or draggable items, and to handle the drag and drop process.</p>
+
+<div class="index">
+<ul>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/DataTransfer"><code>DataTransfer</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/DataTransferItem"><code>DataTransferItem</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/DataTransferItemList"><code>DataTransferItemList</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/DragEvent"><code>DragEvent</code></a></span></span></li>
+</ul>
+</div>
+
+<h3 id="Page_history_interfaces">Page history interfaces</h3>
+
+<p>The History API interfaces let you access information about the browser's history, as well as to shift the browser's current tab forward and backward through that history.</p>
+
+<div class="index">
+<ul>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/BeforeUnloadEvent"><code>BeforeUnloadEvent</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HashChangeEvent"><code>HashChangeEvent</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/History"><code>History</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/Location"><code>Location</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/PageTransitionEvent"><code>PageTransitionEvent</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/PopStateEvent"><code>PopStateEvent</code></a></span></span></li>
+</ul>
+</div>
+
+<h3 id="Web_Components_interfaces">Web Components interfaces</h3>
+
+<p>These interfaces are used by the <a href="/en-US/docs/Web/Web_Components">Web Components API</a> to create and manage the available <a href="/en-US/docs/Web/Web_Components/Using_custom_elements">custom elements</a>.</p>
+
+<div class="index">
+<ul>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/CustomElementRegistry"><code>CustomElementRegistry</code></a></span></span></li>
+</ul>
+</div>
+
+<h3 id="Miscellaneous_and_supporting_interfaces">Miscellaneous and supporting interfaces</h3>
+
+<p>These supporting object types are used in a variety of ways in the HTML DOM API; in addition, {{domxref("PromiseRejectionEvent")}} represents the event delivered when a {{Glossary("JavaScript")}} {{jsxref("Promise")}} is rejected.</p>
+
+<div class="index">
+<ul>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/DOMStringList"><code>DOMStringList</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/DOMStringMap"><code>DOMStringMap</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/ErrorEvent"><code>ErrorEvent</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/HTMLAllCollection"><code>HTMLAllCollection</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/MimeType"><code>MimeType</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/MimeTypeArray"><code>MimeTypeArray</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/PromiseRejectionEvent"><code>PromiseRejectionEvent</code></a></span></span></li>
+</ul>
+</div>
+
+<h3 id="Interfaces_belonging_to_other_APIs">Interfaces belonging to other APIs</h3>
+
+<p>There are several interfaces which are technically defined in the HTML specification while actually being part of other APIs.</p>
+
+<h4 id="Web_storage_interfaces">Web storage interfaces</h4>
+
+<p>The <a href="/en-US/docs/Web/API/Web_Storage_API">Web Storage API</a> provides the ability for web sites to store data either temporarily or permanently on the user's device for later re-use.</p>
+
+<div class="index">
+<ul>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/Storage"><code>Storage</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/StorageEvent"><code>StorageEvent</code></a></span></span></li>
+</ul>
+</div>
+
+<h4 id="Web_Workers_interfaces">Web Workers interfaces</h4>
+
+<p>These interfaces are used by the <a href="/en-US/docs/Web/API/Web_Workers_API">Web Workers API</a> both to establish the ability for workers to interact with an app and its content, but also to support messaging between windows or apps.</p>
+
+<div class="index">
+<ul>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/BroadcastChannel"><code>BroadcastChannel</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/DedicatedWorkerGlobalScope"><code>DedicatedWorkerGlobalScope</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/MessageChannel"><code>MessageChannel</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/MessageEvent"><code>MessageEvent</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/MessagePort"><code>MessagePort</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/SharedWorker"><code>SharedWorker</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/SharedWorkerGlobalScope"><code>SharedWorkerGlobalScope</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/Worker"><code>Worker</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/WorkerGlobalScope"><code>WorkerGlobalScope</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/WorkerLocation"><code>WorkerLocation</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/WorkerNavigator "><code>WorkerNavigator </code></a></span></span></li>
+</ul>
+</div>
+
+<h4 id="WebSocket_interfaces">WebSocket interfaces</h4>
+
+<p>These interfaces, defined by the HTML specification, are used by the <a href="/en-US/docs/Web/API/WebSockets_API">WebSocket API</a>.</p>
+
+<div class="index">
+<ul>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/CloseEvent"><code>CloseEvent</code></a></span></span></li>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/WebSocket"><code>WebSocket</code></a></span></span></li>
+</ul>
+</div>
+
+<h4 id="Server-sent_events_interfaces">Server-sent events interfaces</h4>
+
+<p>The {{domxref("EventSource")}} interface represents the source which sent or is sending <a href="/en-US/docs/Web/API/Server-sent_events">server-sent events</a>.</p>
+
+<div class="index">
+<ul>
+ <li><span class="indexListRow"><span class="indexListTerm"><a href="/en-US/docs/Web/API/EventSource"><code>EventSource</code></a></span></span></li>
+</ul>
+</div>
+
+<h2 id="Examples">Examples</h2>
+
+<p>In this example, an {{HTMLElement("input")}} element's {{domxref("HTMLInputElement.input_event", "input")}} event is monitored in order to update the state of a form's "submit" button based on whether or not a given field currently has a value.</p>
+
+<h4 id="JavaScript">JavaScript</h4>
+
+<pre class="brush: js">const nameField = document.getElementById("userName");
+const sendButton = document.getElementById("sendButton")
+
+sendButton.disabled = true;
+// [note: this is disabled since it causes this article to always load with this example focused and scrolled into view]
+//nameField.focus();
+
+nameField.addEventListener("input", event =&gt; {
+ const elem = event.target;
+ const valid = elem.value.length != 0;
+
+ if (valid &amp;&amp; sendButton.disabled) {
+ sendButton.disabled = false;
+ } else if (!valid &amp;&amp; !sendButton.disabled) {
+ sendButton.disabled = true;
+ }
+});</pre>
+
+<p>This code uses the {{domxref("Document")}} interface's {{domxref("Document.getElementById", "getElementById()")}} method to get the DOM object representing the {{HTMLElement("input")}} elements whose IDs are <code>userName</code> and <code>sendButton</code>.  With these, we can access the properties and methods that provide information about and grant control over these elements.</p>
+
+<p>The {{domxref("HTMLInputElement")}} object for the "Send" button's {{domxref("HTMLInputElement.disabled", "disabled")}} property is set to <code>true</code>, which disables the "Send" button so it can't be clicked. In addition, the user name input field is made the active focus by calling the {{domxref("HTMLElement.focus", "focus()")}} method it inherits from {{domxref("HTMLElement")}}.</p>
+
+<p>Then {{domxref("EventTarget.addEventListener", "addEventListener()")}} is called to add a handler for the <code>input</code> event to the user name input. This code looks at the length of the current value of the input; if it's zero, then the "Send" button is disabled if it's not already disabled. Otherwise, the code ensures that the button is enabled.</p>
+
+<p>With this in place, the "Send" button is always enabled whenever the user name input field has a value, and disabled when it's empty.</p>
+
+<h4 id="HTML">HTML</h4>
+
+<p>The HTML for the form looks like this:</p>
+
+<pre class="brush: html">&lt;p&gt;Please provide the information below. Items marked with "*" are required.&lt;/p&gt;
+&lt;form action="" method="get"&gt;
+  &lt;p&gt;
+    &lt;label for="userName" required&gt;Your name:&lt;/label&gt;
+    &lt;input type="text" id="userName"&gt; (*)
+  &lt;/p&gt;
+  &lt;p&gt;
+    &lt;label for="email"&gt;Email:&lt;/label&gt;
+    &lt;input type="email" id="userEmail"&gt;
+  &lt;/p&gt;
+  &lt;input type="submit" value="Send" id="sendButton"&gt;
+&lt;/form&gt;
+</pre>
+
+<h4 id="Result">Result</h4>
+
+<p>{{EmbedLiveSample("Examples", 640, 300)}}</p>
+
+<h2 id="Specifications">Specifications</h2>
+
+<table class="standard-table">
+ <thead>
+ <tr>
+ <th scope="col">Specification</th>
+ <th scope="col">Status</th>
+ <th scope="col">Comment</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td>{{SpecName('HTML WHATWG')}}</td>
+ <td>{{Spec2('HTML WHATWG')}}</td>
+ <td>WHATWG HTML Specification</td>
+ </tr>
+ <tr>
+ <td>{{SpecName('HTML5 W3C')}}</td>
+ <td>{{Spec2('HTML5 W3C')}}</td>
+ <td>No change from {{SpecName("DOM2 HTML")}}</td>
+ </tr>
+ <tr>
+ <td>{{SpecName('DOM2 HTML')}}</td>
+ <td>{{Spec2('DOM2 HTML')}}</td>
+ <td>No change from {{SpecName("DOM1")}}.</td>
+ </tr>
+ <tr>
+ <td>{{SpecName('DOM1')}}</td>
+ <td>{{Spec2('DOM1')}}</td>
+ <td>Initial definition.</td>
+ </tr>
+ </tbody>
+</table>
+
+<h2 id="Browser_compatibility">Browser compatibility</h2>
+
+<div>
+
+
+<p>{{Compat("api.HTMLElement")}}</p>
+</div>
+
+<h2 id="See_also">See also</h2>
+
+<dl>
+ <dt>References</dt>
+ <dd>
+ <ul>
+ <li><a href="/en-US/docs/Web/HTML/Element">HTML elements reference</a></li>
+ <li><a href="/en-US/docs/Web/HTML/Attributes">HTML attribute reference</a></li>
+ <li><a href="/en-US/docs/Web/API/Document_Object_Model">Document Object Model (DOM)</a> reference</li>
+ </ul>
+ </dd>
+ <dt>Guides</dt>
+ <dd>
+ <ul>
+ <li>
+ <p><a href="/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Manipulating_documents" style="font-size: 1rem; letter-spacing: -0.00278rem;">Manipulating documents</a><span style="font-size: 1rem; letter-spacing: -0.00278rem;">: A beginner's guide to manipulating the DOM.</span></p>
+ </li>
+ </ul>
+ </dd>
+</dl>
diff --git a/files/uk/web/api/html_dom_api/microtask_guide/index.html b/files/uk/web/api/html_dom_api/microtask_guide/index.html
new file mode 100644
index 0000000000..7b02378a59
--- /dev/null
+++ b/files/uk/web/api/html_dom_api/microtask_guide/index.html
@@ -0,0 +1,324 @@
+---
+title: Використання мікрозадач у JavaScript за допомогою queueMicrotask()
+slug: Web/API/HTML_DOM_API/Microtask_guide
+tags:
+ - API
+ - JavaScript
+ - ServiceWorker
+ - SharedWorker
+ - Window
+ - Worker
+ - queueMicrotask
+ - Довідник
+ - асинхронний
+ - мікрозадача
+ - пакет
+ - черга
+translation_of: Web/API/HTML_DOM_API/Microtask_guide
+---
+<p>{{APIRef("HTML DOM")}}</p>
+
+<p><span class="seoSummary"><strong>Мікрозадача</strong> - це коротка функція, яка виконується після того, як функція чи програма, яка її створила, завершується, <em>та</em> тільки якщо стек виконання JavaScript порожній, але перед поверненням контролю до циклу подій {{Glossary("user agent", "користувацького агента")}} для керування середовищем виконання скрипта.</span> Даний цикл подій може бути або головним циклом подій веб-переглядача, або циклом подій, що керує <a href="/uk/docs/Web/API/Web_Workers_API">веб-виконавцем</a>. Це дозволяє даній функції виконуватись без ризику втрутитись у виконання іншого скрипта, в той же час гарантує, що мікрозадача виконається до того, як користувацький агент матиме змогу відреагувати на дії, виконані цією мікрозадачею.</p>
+
+<p><a href="/uk/docs/Web/JavaScript/Reference/Global_Objects/Promise">Проміси</a> JavaScript та <a href="/uk/docs/Web/API/Mutation_Observer_API">Mutation Observer API</a> використовують чергу мікрозадач для виконання своїх зворотніх викликів, але бувають інші випадки, коли здатність відкласти роботу до завершення поточного проходу циклу подій може бути корисна. Щоб дозволити стороннім бібліотекам, фреймворкам та поліфілам використовувати мікрозадачі, метод {{domxref("WindowOrWorkerGlobalScope.queueMicrotask", "queueMicrotask()")}} доступний у інтерфейсах {{domxref("Window")}} та {{domxref("Worker")}} через домішку {{domxref("WindowOrWorkerGlobalScope")}}.</p>
+
+<h2 id="Задачі_та_мікрозадачі">Задачі та мікрозадачі</h2>
+
+<p>Щоб належно обговорювати мікрозадачі, насамперед, корисно знати, що таке задача JavaScript та чим мікрозадачі відрізняються від задач. Це швидке, спрощене пояснення, але якщо вам потрібно більше подробиць, ви можете їх дізнатись у статті <a href="/uk/docs/Web/API/HTML_DOM_API/Microtask_guide/In_depth">В подробицях: мікрозадачі та середовище виконання JavaScript</a>.</p>
+
+<h3 id="Задачі">Задачі</h3>
+
+<p><strong>Задача</strong> - це будь-який код JavaScript, що запланований до запуску стандартними механізмами, такими як початковий запуск програми, запуск зворотного виклику для події, або запуск таймера чи інтервалу. Всі вони розташовуються у <strong>черзі задач</strong>.</p>
+
+<p>Задачі додаються до черги задач, коли:</p>
+
+<ul>
+ <li>Безпосередньо виконується нова програма чи підпрограма JavaScript (наприклад, з консолі чи запуском коду у елементі {{HTMLElement("script")}}).</li>
+ <li>Спрацьовує подія, додаючи функцію зворотного виклику події до черги задач.</li>
+ <li>Доходить черга таймера чи інтервалу, створеного методом {{domxref("WindowOrWorkerGlobalScope.setTimeout", "setTimeout()")}} чи {{domxref("WindowOrWorkerGlobalScope.setInterval", "setInterval()")}}, що спричиняє додавання відповідного зворотного виклику до черги задач.</li>
+</ul>
+
+<p>Цикл подій, що керує вашим кодом, обробляє ці задачі одна за одною, в тому порядку, в якому вони були додані у чергу. Лише ті задачі, які <em>вже знаходились у черзі задач</em>, коли почався прохід циклу подій, будуть виконані протягом поточної ітерації. Решті доведеться зачекати наступної ітерації.</p>
+
+<h3 id="Мікрозадачі">Мікрозадачі</h3>
+
+<p>Спершу різниця між мікрозадачами та задачами здається незначною. І вони дійсно схожі; і те, й інше - код JavaScript, який розміщується у черзі та запускається у належний час. Однак, в той час, як цикл подій запускає лише задачі, наявні у черзі на момент початку ітерації, одна за одною, з мікрозадачами він поводиться зовсім по-іншому.</p>
+
+<p>Є дві ключові відмінності.</p>
+
+<p>По-перше, кожен раз, коли задача завершується, цикл подій перевіряє, чи задача повертає контроль іншому коду JavaScript. Якщо ні, він запускає всі мікрозадачі з черги мікрозадач. Таким чином, черга мікрозадач обробляється багаторазово протягом однієї ітерації циклу подій, в тому числі після обробки подій та інших зворотних викликів.</p>
+
+<p>По-друге, якщо мікрозадача додає інші мікрозадачі до черги, викликаючи метод {{domxref("WindowOrWorkerGlobalScope.queueMicrotask", "queueMicrotask()")}}, ці додані мікрозадачі <em>виконуються перед запуском наступної задачі</em>. Все тому, що цикл подій викликатиме мікрозадачі, доки у черзі не залишиться жодної, навіть якщо при цьому додаються нові.</p>
+
+<div class="blockIndicator warning">
+<p><strong>Застереження:</strong> Оскільки мікрозадачі можуть ставити у чергу інші мікрозадачі, а цикл подій продовжуватиме обробляти мікрозадачі, доки черга не спорожніє, існує реальний ризик спричинити нескінченну обробку мікрозадач циклом подій. Будьте обережні, додаючи мікрозадачі рекурсивно.</p>
+</div>
+
+<h2 id="Використання_мікрозадач">Використання мікрозадач</h2>
+
+<p>Перед тим, як продовжити, важливо зазначити ще раз, що більшість програмістів нечасто використовують мікрозадачі, якщо взагалі використовують. Це вузькоспеціалізована функціональність сучасної JavaScript-розробки для переглядачів, що дозволяє вам запланувати виконання коду попереду чогось іншого у довгому списку речей, що чекають на виконання комп'ютером користувача. Зловживання цією можливістю призведе до проблем з продуктивністю.</p>
+
+<h3 id="Додавання_мікрозадач_у_чергу">Додавання мікрозадач у чергу</h3>
+
+<p>Таким чином, вам варто використовувати мікрозадачі лише тоді, коли немає іншого рішення, або при створенні фреймворків чи бібліотек, які мають використовувати мікрозадачі для створення функціональності, яку реалізують. Хоча раніше існували трюки, які дозволяли ставити мікрозадачі в чергу (наприклад, створення проміса, який негайно вирішується), введення методу {{domxref("WindowOrWorkerGlobalScope.queueMicrotask", "queueMicrotask()")}} додає стандартний спосіб створення мікрозадач безпечно та без допомоги трюків.</p>
+
+<p>Введення методу <code>queueMicrotask()</code> дозволяє уникнути вивертів, що трапляються під час такого проникнення у чергу мікрозадач за допомогою промісів. Наприклад, при використанні промісів для створення мікрозадач, винятки, викинуті зворотним викликом, повідомляються як відхилені проміси, а не як стандартні винятки. Також, створення та знищення промісів потребує додаткових витрат як часу, так і пам'яті, цього уникає функція, яка належним чином ставить мікрозадачі у чергу.</p>
+
+<p>Просто передайте {{jsxref("Function","функцію")}} JavaScript, яку треба викликати, коли контекст обробляє мікрозадачі, у метод <code>queueMicrotask()</code>, доступний у глобальному контексті, як визначено у інтерфейсі {{domxref("Window")}} або {{domxref("Worker")}}, в залежності від поточного контексту виконання.</p>
+
+<pre class="brush: js">queueMicrotask(() =&gt; {
+ /* тут код, який виконує мікрозадача */
+});
+</pre>
+
+<p>Сама функція мікрозадачі не приймає параметрів та не повертає значення.</p>
+
+<h3 id="Коли_використовувати_мікрозадачі">Коли використовувати мікрозадачі</h3>
+
+<p>У цьому розділі ми розглянемо сценарії, в яких мікрозадачі є особливо корисними. Загалом, мова йде про отримання та перевірку результатів, або прибирання, після того, як головне тіло контексту виконання JavaScript завершується, але перед тим, як опрацьовуються будь-які обробники подій, таймери та інтервали, чи інші зворотні виклики.</p>
+
+<p>Коли це корисно?</p>
+
+<p>Головна причина використання мікрозадач проста: забезпечити послідовний порядок виконання задач, навіть коли результати чи дані доступні синхронно, одночасно знижуючи ризик помітних користувачу затримок у операціях.</p>
+
+<h4 id="Забезпечення_порядку_виконання_при_використанні_промісів_в_умовних_конструкціях">Забезпечення порядку виконання при використанні промісів в умовних конструкціях</h4>
+
+<p>Одна з ситуацій, в якій можуть використовуватись мікрозадачі - це забезпечення завжди послідовного порядку виконання у ситуації, коли проміси використовуються у одному блоці конструкції <code>if...else</code> (чи іншої умовної конструкції), але не в іншому блоці. Розглянемо наступний код:</p>
+
+<pre class="brush: js">customElement.prototype.getData = url =&gt; {
+ if (this.cache[url]) {
+ this.data = this.cache[url];
+ this.dispatchEvent(new Event("load"));
+ } else {
+ fetch(url).then(result =&gt; result.arrayBuffer()).then(data =&gt; {
+ this.cache[url] = data;
+ this.data = data;
+ this.dispatchEvent(new Event("load"));
+ });
+ }
+};</pre>
+
+<p>Проблема тут полягає в тому, що, використовуючи задачу в одній гілці конструкції <code>if...else</code> (у випадку, коли зображення доступне з кешу), але маючи проміси у блоці <code>else</code>, ми отримуємо ситуацію, в якій порядок операцій може бути різним; наприклад, як показано нижче.</p>
+
+<pre class="brush: js">element.addEventListener("load", () =&gt; console.log("Завантажені дані"));
+console.log("Отримання даних...");
+element.getData();
+console.log("Дані отримано");
+</pre>
+
+<p>Виконання цього коду два рази підряд дає результати, наведені у таблиці:</p>
+
+<table class="standard-table">
+ <caption>Результати, коли дані не кешовані (зліва) та коли дані знайдені в кеші</caption>
+ <thead>
+ <tr>
+ <th scope="col">Дані не кешовані</th>
+ <th scope="col">Дані кешовані</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td>
+ <pre>
+Отримання даних
+Дані отримано
+Завантажені дані
+</pre>
+ </td>
+ <td>
+ <pre>
+Отримання даних
+Завантажені дані
+Дані отримано
+</pre>
+ </td>
+ </tr>
+ </tbody>
+</table>
+
+<p>Навіть гірше, іноді властивість елементів <code>data</code> буде встановлена, а іноді не буде, на той момент, коли цей код завершує виконання.</p>
+
+<p>Ми можемо забезпечити послідовний порядок цих операцій використанням мікрозадачі у блоці <code>if</code>, щоб збалансувати два блоки:</p>
+
+<pre class="brush: js">customElement.prototype.getData = url =&gt; {
+ if (this.cache[url]) {
+ queueMicrotask(() =&gt; {
+ this.data = this.cache[url];
+ this.dispatchEvent(new Event("load"));
+ });
+ } else {
+ fetch(url).then(result =&gt; result.arrayBuffer()).then(data =&gt; {
+ this.cache[url] = data;
+ this.data = data;
+ this.dispatchEvent(new Event("load"));
+ });
+ }
+};</pre>
+
+<p>Це збалансовує два блоки, бо тепер в обох ситуаціях встановлення значення <code>data</code> та запуск події <code>load</code> відбувається всередині мікрозадачі (за допомогою <code>queueMicrotask()</code> у блоці <code>if</code> та за допомогою промісів, що використовуються методом {{domxref("WindowOrWorkerGlobalScope.fetch", "fetch()")}}, у блоці <code>else</code>).</p>
+
+<h4 id="Пакетне_виконання_операцій">Пакетне виконання операцій</h4>
+
+<p>Ви також можете використати мікрозадачі, щоб зібрати множину запитів з різних джерел у єдиний пакет, уникаючи можливих затрат, пов'язаних з багатьма викликами задля виконання задач одного типу.</p>
+
+<p>Фрагмент коду, наведений нижче, створює функцію, яка збирає множину повідомлень у масив, використовуючи мікрозадачу, щоб відправити їх як єдиний об'єкт по завершенні контексту.</p>
+
+<pre class="brush: js">const messageQueue = [];
+
+let sendMessage = message =&gt; {
+ messageQueue.push(message);
+
+ if (messageQueue.length === 1) {
+ queueMicrotask(() =&gt; {
+ const json = JSON.stringify(messageQueue);
+ messageQueue.length = 0;
+ fetch("url-of-receiver", json);
+ });
+ }
+};
+</pre>
+
+<p>Коли викликається <code>sendMessage()</code>, вказане повідомлення спочатку додається у масив черги повідомлень. А далі відбувається цікаве.</p>
+
+<p>Якщо повідомлення, яке ми додали до масиву, є першим, ми додаємо мікрозадачу, яка відправлятиме пакет. Мікрозадача виконається, як завжди, коли шлях виконання JavaScript сягне верхнього рівня, одразу перед зворотними викликами. Це означає, що будь-які подальші виклики <code>sendMessage()</code>, зроблені в цей час, додадуть свої повідомлення до черги повідомлень, але, завдяки перевірці довжини масиву перед додаванням мікрозадачі, нових мікрозадач у чергу не буде додано.</p>
+
+<p>Коли запускається мікрозадача, то вона має масив, потенційно, багатьох повідомлень, які на неї очікують. Вона починається кодуванням його як JSON за допомогою методу {{jsxref("JSON.stringify()")}}. Після цього вміст масиву більше не потрібний, а отже, ми спорожнюємо масив <code>messageQueue</code>. Нарешті, ми використовуємо метод {{domxref("WindowOrWorkerGlobalScope.fetch", "fetch()")}}, щоб відправити рядок JSON на сервер.</p>
+
+<p>Це дозволяє кожному виклику <code>sendMessage()</code>, зробленому під час тієї самої ітерації циклу подій, додавати свої повідомлення до тієї самої операції <code>fetch()</code>, без потенційних затримок трансмісії іншими задачами, такими як таймери та подібні.</p>
+
+<p>Сервер отримає рядок JSON, далі, ймовірно, декодує його та обробить повідомлення, які знайде у отриманому масиві.</p>
+
+<h2 id="Приклади">Приклади</h2>
+
+<h3 id="Простий_приклад_мікрозадачі">Простий приклад мікрозадачі</h3>
+
+<p>У цьому простому прикладі ми бачимо, що додавання мікрозадачі у чергу спричиняє запуск зворотного виклику мікрозадачі після того, як тіло цього скрипта верхнього рівня завершує виконання.</p>
+
+<div class="hidden">
+<h4 id="HTML">HTML</h4>
+
+<pre class="brush: html">&lt;pre id="log"&gt;
+&lt;/pre&gt;</pre>
+</div>
+
+<h4 id="JavaScript">JavaScript</h4>
+
+<div class="hidden">
+<p>Наведений нижче код використовується для логування результату.</p>
+
+<pre class="brush: js">let logElem = document.getElementById("log");
+let log = s =&gt; logElem.innerHTML += s + "&lt;br&gt;";</pre>
+</div>
+
+<p>У наступному коді ми бачимо виклик {{domxref("WindowOrWorkerGlobalScope.queueMicrotask", "queueMicrotask()")}}, що використовується для планування запуску мікрозадачі. Цей виклик оточують виклики <code>log()</code>, користувацької функції, яка просто виводить текст на екран.</p>
+
+<pre class="brush: js">log("До розміщення мікрозадачі в черзі");
+queueMicrotask(() =&gt; {
+ log("Мікрозадача запустилась.")
+});
+log("Після розміщення мікрозадачі в черзі");</pre>
+
+<h4 id="Результат">Результат</h4>
+
+<p>{{EmbedLiveSample("Простий_приклад_мікрозадачі", 640, 80)}}</p>
+
+<h3 id="Таймер_та_приклад_мікрозадачі">Таймер та приклад мікрозадачі</h3>
+
+<p>У цьому прикладі встановлюється таймер для запуску через нуль мілісекунд (або "якомога швидше"). Це демонструє різницю між тим, що означає "якомога швидше" при плануванні нової задачі (наприклад, при використанні <code>setTimeout()</code>) у порівнянні з використанням мікрозадачі.</p>
+
+<div class="hidden">
+<h4 id="HTML_2">HTML</h4>
+
+<pre class="brush: html">&lt;pre id="log"&gt;
+&lt;/pre&gt;</pre>
+</div>
+
+<h4 id="JavaScript_2">JavaScript</h4>
+
+<div class="hidden">
+<p>Наведений нижче код використовується для логування результату.</p>
+
+<pre class="brush: js">let logElem = document.getElementById("log");
+let log = s =&gt; logElem.innerHTML += s + "&lt;br&gt;";</pre>
+</div>
+
+<p>У наступному коді ми бачимо виклик {{domxref("WindowOrWorkerGlobalScope.queueMicrotask", "queueMicrotask()")}}, який використовується для планування запуску мікрозадачі. Цей виклик розташований між викликами <code>log()</code>, користувацької функції, яка просто виводить текст на екран.</p>
+
+<p>Наступний код встановлює таймер, який має запуститися через нуль мілісекунд, після чого додає у чергу мікрозадачу. Він оточений викликами <code>log()</code> для виводу додаткових повідомлень.</p>
+
+<pre class="brush: js">let callback = () =&gt; log("Запустився звичайний зворотний виклик таймера");
+
+let urgentCallback = () =&gt; log("*** О, ні! Запустився терміновий зворотний виклик!");
+
+log("Початок головної програми");
+setTimeout(callback, 0);
+queueMicrotask(urgentCallback);
+log("Кінець головної програми");</pre>
+
+<h4 id="Результат_2">Результат</h4>
+
+<p>{{EmbedLiveSample("Таймер_та_приклад_мікрозадачі", 640, 100)}}</p>
+
+<p>Зауважте, що текст, який виводиться головною програмою, з'являється першим, далі текст, виведений мікрозадачею, а за ним текст зворотного виклику таймера. Все тому, що, коли задача, що керує виконанням головної програми, завершується, черга мікрозадач обробляється раніше черги задач, в якій розташований зворотний виклик таймера. Знання того, що задачі та мікрозадачі розташовуються у різних чергах, і те, що мікрозадачі виконуються першими, допомагає легше в цьому розібратись.</p>
+
+<h3 id="Мікрозадача_з_функції">Мікрозадача з функції</h3>
+
+<p>Цей приклад трохи розширює попередній додаванням функції, яка виконує певну роботу. Ця функція використовує <code>queueMicrotask()</code>, щоб додати мікрозадачу. Важливий момент, який варто з нього винести - мікрозадача не виконується, коли завершується функція, а тільки коли завершується головна програма.</p>
+
+<div class="hidden">
+<h4 id="HTML_3">HTML</h4>
+
+<pre class="brush: html">&lt;pre id="log"&gt;
+&lt;/pre&gt;</pre>
+</div>
+
+<h4 id="JavaScript_3">JavaScript</h4>
+
+<div class="hidden">
+<p>Наведений нижче код використовується для логування результату.</p>
+
+<pre class="brush: js">let logElem = document.getElementById("log");
+let log = s =&gt; logElem.innerHTML += s + "&lt;br&gt;";</pre>
+</div>
+
+<p>Код головної програми наступний. Функція <code>doWork()</code> викликає <code>queueMicrotask()</code>, але мікрозадача не запускається, доки вся програма не завершується, оскільки саме тоді завершується задача і не залишається нічого іншого у стеку виконання.</p>
+
+<pre class="brush: js">let callback = () =&gt; log("Запустився звичайний зворотний виклик таймера");
+
+let urgentCallback = () =&gt; log("*** О, ні! Запустився терміновий зворотний виклик!");
+
+let doWork = () =&gt; {
+ let result = 1;
+
+ queueMicrotask(urgentCallback);
+
+ for (let i=2; i&lt;=10; i++) {
+ result *= i;
+ }
+ return result;
+};
+
+log("Початок головної програми");
+setTimeout(callback, 0);
+log(`10! дорівнює ${doWork()}`);
+log("Кінець головної програми");</pre>
+
+<h4 id="Результат_3">Результат</h4>
+
+<p>{{EmbedLiveSample("Мікрозадача_з_функції", 640, 100)}}</p>
+
+<h2 id="Див._також">Див. також</h2>
+
+<ul>
+ <li><a href="/uk/docs/Web/API/HTML_DOM_API/Microtask_guide/In_depth">В подробицях: мікрозадачі та середовище виконання JavaScript</a></li>
+ <li>{{domxref("WindowOrWorkerGlobalScope.queueMicrotask", "queueMicrotask()")}}</li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Asynchronous">Asynchronous JavaScript</a>
+ <ul>
+ <li><a href="/en-US/docs/Learn/JavaScript/Asynchronous/Concepts">General asynchronous programming concepts</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Asynchronous/Introducing">Introducing asynchronous JavaScript</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Asynchronous/Timeouts_and_intervals">Cooperative asynchronous JavaScript: Timeouts and intervals</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Asynchronous/Promises">Graceful asynchronous programming with Promises</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Asynchronous/Choosing_the_right_approach">Choosing the right approach</a></li>
+ </ul>
+ </li>
+</ul>