An overview of the

This article takes a look at some of the most important content in HTML, mainly from HTML Spec, for a more complete introduction.

Event

Js uses an asynchronous, event-driven programming model. A complete event is required to contain

  • An Event object, an Event
  • An EventTarget object, called an EventTarget, is typically a dom element, can be a window, or something else, such as XMLHttpRequest
  • An event listener, eventHandler, is a callback function when listening for an event
  • Event dispatch Action

The event object

Events in browsers are based on Event classes, such as MouseEvent. In addition to these built-in events, you can also customize events, either directly by instantiating events or customEvents, which add custom data.

// add an appropriate event listener
obj.addEventListener("cat", function(e) { process(e.detail) });

// create and dispatch the event
var event = new CustomEvent("cat", {
  detail: {
    hazcheeseburger: true
  }
});
obj.dispatchEvent(event);
Copy the code

Event Target Object

An EventTarget is an object that can bind event handlers and distribute events.

The EventTarget objects in the browser are eventtargets and their word classes, such as the common Element, Document, and Window classes, as well as XMLHttpRequest, AudioNode, AudioContext, and so on.

Event listener

Event listeners can be used in three ways

  • Set the event handler properties
el.onclick=(e)=>{}
Copy the code
  • HTML inline event, the content is a string
 onclick="console.log('Thank you');"
Copy the code
  • addEventListener()
Three arguments, the first is the event type, the second is the event handler function and the third is options or useCapture. The default value is false. When an object contains properties 1. Capture, the value is handled in the capture phase. 2. If true, preventDefault() will never be called, so it's not necessary to wait for the main thread to cancel the default event and generate the frame. Chrome and other browsers default to true for document level nodes. Its abort() method is called when the listener is removed. See the next chapterCopy the code

Event dispatch Action

An event can be triggered a user of a behavior, such as a mouse click, can also be triggered programming, such as the HTMLElement. Click (), and similar EventTarget. DispatchEvent ()

Other details

Event propagation

Event propagation consists of three phases

  • capturing
  • target
  • bubble

Note that the “focus,” “blur,” and “Scroll” events do not bubble, and the load events other than the entire document will bubble until the document ends.

Adding an event handler directly to the body element handles events on the window, so bubbles after the Document.

Event cancellation

Call preventDefault() to cancel the default behavior and stopPropagation with stopPropagation()

MutationObserver

Provides the ability to monitor changes in the DOM tree and trigger event handlers when the TREE changes

const targetNode = document.querySelector("#someElement"); const observerOptions = { childList: true, attributes: true, // Omit (or set to false) to observe only changes to the parent node subtree: true } const observer = new MutationObserver(callback); Observe.observe (targetNode, observerOptions); // Create an observer containing the event handler's callback observer.observe(targetNode, observerOptions); // Add monitoringCopy the code

Aborting ongoing activities

Provides an API to cancel requests such as promises, such as the addEventListener() that can be used in fetch or the one described earlier.

The AbortController instance has an attribute, signal, and an abort() instance method, for example

var controller = new AbortController(); var signal = controller.signal; var downloadBtn = document.querySelector('.download'); var abortBtn = document.querySelector('.abort'); downloadBtn.addEventListener('click', fetchVideo); abortBtn.addEventListener('click', function() { controller.abort(); console.log('Download aborted'); }); function fetchVideo() { ... fetch(url, {signal}).then(function(response) { ... }).catch(function(e) { reports.textContent = 'Download error: ' + e.message; })}Copy the code

Node and its subclasses

Node inherits from EventTarget and provides a series of APIS for adding, deleting, modifying and viewing Node instances, known as the DOM API.

node type

The node. nodeType attribute is an integer representing the specific Node type, including

  • Node. ELEMENT_NODE element (1)
  • Node.ATTRIBUTE_NODE (2) Element attribute
  • Text in node.text_node (3) element or attribute
  • Node.CDATA_SECTION_NODE (4) such as .
  • Node.PROCESSING_INSTRUCTION_NODE (7) such as .
  • Node.COM MENT_NODE (8) comments
  • DOCUMENT_NODE (9) Document Node
  • Node.DOCUMENT_TYPE_NODE (10) such as
  • Node. DOCUMENT_FRAGMENT_NODE (11)

The categories of these nodes we’ll focus on are 1 and 9.

Document

Document.documentelement represents an HTML page in which the HTML element and body element can be obtained via document.documentElement and document.body, respectively

It can also be used to access many document-level properties, such as document.domain.

Element

Elements in HTML documents are subclasses of Element or, more accurately, HTMLElement. For example, each div Element is an instance of the HTMLDivElement class, where available methods and attributes are inherited from other classes as well as their own.

In HTML, the instantiation of most classes requires the provided factory functions

document.createElement(tagName[, options])
Copy the code

There are also elements that can be called directly new, such as

New Image() // equivalent to document.createElement('img')Copy the code

In addition to the browser-provided elements, we can also encapsulate our own elements, called Web Components

Element classification

Elements are classified according to the Content Model, which defines what an element can contain.

Html4 divides elements into two broad categories

  • Inline Inline elements can only contain text and other inline elements, and do not need to take a separate line, such as span, during rendering
  • Block-level, block-level elements can contain other block-level elements or inline-elements that need to be rendered on a separate line, such as div.

Other elements that can be either inline, such as a button element inside another inline element, can no longer contain block-levels.

These concepts have been reclassified in HTML5 because they are easily confused with the display property in CSS.

There are seven categories in the new edition

  • Metadata Content Describes document information, including
  • Most of the molecular elements in the Flow Content body are
  • Sectioning content
  • Heading content
  • Phrasing content
  • Embedded Content is used to embed other content
  • Interactive Content Is used for interaction

In this section we will focus only on the effects of script tag defer and async properties on normal Scripts and models.

Web application APIs

Web pages typically run in a browser, which provides other apis, such as input and output, in addition to the JS engine implemented according to the ECMA specification.

There are several ways to make JS execute in the context of a document, including but not limited to:

  • Processing of script elements
  • Navigate using javascript: URLs
  • Event Handlers, for example by setting element attributes
  • Script functionality of SVG

realm

Ecma introduces the concept of a realm, which represents the global environment in which scripts run. Each realm has a GlobalObject (as [[GlobalObject]]), defined by the mount specification on the GlobalObject and its properties.

Event loops

To coordinate events, user interactions, scripts, rendering, network requests, and so on, the user agent must use the Event loop described in this section

Event loops do not correspond to each thread; for example, multiple event loops can correspond to one thread.

An event loop has one or more Task queues, i.e. a series of tasks. Note that task queues are not queues, but sets.

The tasks encapsulate algorithm corresponds to the following Works

  • Event
  • Parsing HTML parser
  • The callback callbacks
  • When an algorithm fetches a resource, it is processed by task once the resource is available
  • Reacting to DOM manipulation, such as inserting elements

Microtasks include different hosts that are unified

  • promise

html

  • queueMicrotask
QueueMicrotask (callback) can add a callback to the microtask queue as soon as the call stack is empty, similar to setTimeout(f, 0) but not too much to the microtask queue. Consider using requestAnimationFrame() or requestIdleCallback()Copy the code
  • MutationObserver

node

  • process.nextTick

When a task completes and transfers control to the user agent for the next task (the microtasks generated by the current task will also wait until the current task completes), the microtasks queue will be checked, and the microtasks will also generate microtasks and be added to the microtask queue until the microtasks are empty. This is where the current microtask is executed, the new microtask is executed, the necessary rendering is done, and the next task is performed.

RequestAnimationCallback will be called before rendering, requestIdleCallback will be executed if there is time left on the frame, otherwise skip and the actual rendering will be performed.

Refer to the second half of this sectionhere

communication

MessageEvent represents a MessageEvent that is used in various web communication modes.

Server-sent events

Server-sent Events can be used to make a Server push data to a Web page at any time. The steps can be divided into

  • Instantiate the EventSource, specifying the URL to receive the event
  • Adding Event Listeners

The server sends an event stream of type TEXT /event-stream

See Sse.js for specific implementation

Web sockets

Web Sockets can be used by servers and clients to send information to each other

The current specification only specifies the use of the client side, which creates a WebSocket instance and then calls the corresponding method to send events to the server and listen for events. The server side can be coupled with WS.

Or use socket. IO, which is also wrapped on the client

Cross-document messaging

This refers to cross-document communication, such as between a document and an iframe, or between a document opened with window.open.

This approach can be implemented across domains. Examples can be found here

Channel messaging

Channel Messaging is an upgraded version of the previous one. After the security of the first communication is verified, the communication parties can establish a pipeline.

Broadcasting to other browsing contexts

This is a broadcast form of communication that implements one-to-many.

Don’t cross domain

Web workers

Web workers provide threads other than the main thread that can be used to process calculations outside of the UI (some uI-related browser apis are not accessible). The worker thread and main thread communicate using the cross-document Messaging method.

An ordinary worker, namely an instance of a worker, can only be used by the script that instantiates it, which is called a dicated worker. SharedWorker is also provided, which can be used by multiple scripts of the same origin.