When we write front-end JavaScript programs, the apis we use can be divided into two categories

  1. Browser provides apis: Installed in the browser, such as ES syntax support, DOM API, geolocation API, and audio and video API.
  2. Third party API: not installed in browser by default. Examples include the Twitter API (which allows you to do things like show tweets on your site), the Google Maps API (which empowers custom maps into your site)

This article focuses on the former, but note that some are not fully supported by browsers

Web components

Element reuse and packaging technologies, this API is very confusing and has various implementations, so it is often used to introduce its own web component library (such as Polymer). The rest of the introduction revolves around the latest version, just understand the general idea

The shadow of the DOM

Solve the DOM tree to establish the ability to maintain their own boundaries, including style, child elements

The video TAB is a shadow DOM wrapper with default volume buttons and no trace at all in the source code

Div. CreateShadowRoot (). The appendChild (internal);Copy the code

Custom elements

Custom elements have a lifecycle and introduce a style of object-oriented programming common in JavaScript frameworks

HTML template

The <template> tag provides the DocumentFragment for the location of the page insert elementCopy the code

Atomics ES2017

Provides secure access to SharedArrayBuffer

  • The simplified version of ISA allows multiple contexts to safely read and write a SharedArrayBuffer by forcing only one operation to be performed on the buffer at a time
  • Build complex multithreaded JavaScript programs with as few but stable atomic behaviors as possible
  • Any global context has an Atomics object that exposes a set of static methods for performing thread-safe operations.
  • The browser’s JavaScript compiler and CPU architecture themselves have permission to reorder instructions, which the Atomics API does
  1. The order between all the atomic instructions is never rearranged
  2. Ensure that the order of all instructions relative to atomic read or write instructions does not change (the first is done first, the last is done).
Atomics.add() adds the array element at the specified location to the given value and returns the value of the element before the addition. Atomics.and() associates the array element at the specified position with the given value and returns the value of the element before the operation. Atomics.compareExchange() If the specified element in the array is equal to the given value, updates it to the new value and returns the original value of that element. Atomics.exchange() updates the specified element in the array to the given value and returns the value of the element before it was updated. Atomics.islockfree (size) can be used to check whether the current system supports hardware-level atomic operations. Returns for arrays of the specified size if the current system supports hardware-level atomic operationstrue; Otherwise, it means that for the array, each atomic operation in the Atomics object can only be implemented using a lock. This function is intended for technical experts. Atomics.load() returns the value of the specified element in the array. Atomics.notify() wakes up the threads in the wait queue that are waiting on the element at the specified position in the array. The return value is the number of threads successfully awakened. Atomics.or() equates the array element at the specified position with the given value and returns the value of the element before the operation. Atomics.store() sets the specified element in the array to the given value and returns that value. Atomics.sub() subtracts the array element at the specified location from the given value and returns the value of the element before subtraction. Atomics.wait() tests whether the value at a specified location in the array is still the given value, and if so, suspends until awakened or timed out. The return value is"ok","not-equal""time-out". When called, an exception is thrown if the current thread does not allow blocking (most browsers do not allow wait() on the main thread). Atomics.xor() xor the array element at the specified position with the given value and returns the value of the element before the xor operation.Copy the code

Cross the following message XDM

The postMessage() method allows limited communication between scripts from different execution contexts in an asynchronous manner.

Messaging across Windows, across domains, across pages of different worker threads/sources

Core:

// Target receive source * does not limit the receive sourcePostMessage (message, target receiving source, optional worker thread-related Transferable object)window.postMessage() 
Copy the code

The MESSAGE event is emitted when an XDM message is received

window.addEventListener("message", receiveMessage, false);

function receiveMessage(event)
{
  // For Chrome, the origin property is in the event.originalEvent
  // object.
  // This is not accurate, Chrome does not have this property
  // var origin = event.origin || event.originalEvent.origin;
  var origin = event.origin
  if(origin ! = ="http://example.org:8080")
    return;

  // ...
}
Copy the code

Application: Solve the problem of iframe homology restriction

Cognate: Iframe can passwindow.parent performs arbitrary operations on the parent (manipulating the Dom, triggering events on the parent, etc.) Different sources: The viewer will report errors across sources// Uncaught DOMException: Blocked a frame from accessing a cross-origin frameSubinterface (iframe) callwindow.parent.postMessage() tells the parent to listen for messages sent by the child and process themCopy the code

Encode API

Seamless conversion between string and buffer

Stereotype arrays are specialized arrays for handling numeric types (not all types). Stereotype arrays are not array types. The length of a stereotype array is fixed and cannot be changed after creation.

  • String => stereotype array, encoder always uses UTF-8
  • The encoder supports many string encodings including UTF-8
  • Batch coding [synchronous], stream coding [similar to pipeline]
TexEncoder 
TextEncoderStream
TexDecoder
TextDecoderStream
Copy the code

The File, Blob API

  • Before 2000, the only way to process a file was to put it in a form by setting the input elementType = "file"

Input Gets the local file

  • The File and Blob API is a reliable tool for securely accessing files on client machines and sending and reading large binary objects
  • Blobs identify binary objects
The FileReader type provides the asynchronous file reading mechanism FileReaderSyncCopy the code

Media elements

  • HTML5 has added two new elements, audio and video, to enable the browser to embed audio and video
  • The two elements have a number of properties that determine the current state of the media, and a number of events that monitor changes in the media
  • Not all browsers support all codecs for two elements, which usually means that multiple media sources must be provided. Method to check whether the browser supports a given format and codec.
The play() and pause() methods manually control the playback of media files. The canPlayType () method, which accepts a format/codec stringCopy the code

Drag and drop

  • It can be across panes, browser containers, and even across applications
  • HTML5 imposes a draggable attribute on all elements, indicating whether an element can be dragged
  • By default images, links, and text can be dragged
  • The dataTransfer object transfers data during the drag operation and determines the target to perform the operations dropEffect and dropAllowed

Drop events are triggered in sequence when an element is dragged:

  1. dragstart
  2. Drag will continue to trigger the event as long as it is dragged
  3. dragend
  4. The following events are emitted once an element is dragged to a valid drop target:
  5. The dragenter is triggered when it is dragged to the drop target, similar to a mouseover
  6. This event is emitted while the dragover element is dragged within the drop target range
  7. Dragleave /drop Triggered when an element is dragged outside the drop target

The event preventDefault() method can be used within the listener to override the event behavior of the invalid placed element with the event listener above, converting it to a valid placed element. Note: Different browsers have different default behavior Settings

Notifications API

  • Displaying notifications to users is useful in service workers
  • The page requests Notification permission from the user using the global object Notification, which calls the requestPemission() method, which returns a date.
Notification.requestPermission()
    .then((permission) = >{
        console.log('user respond:',permission);// granted/denied
    });
Copy the code

Constructor implementation creates and displays notification ‘

const n=new Notification('title of notif', {body:'body text'.image:'path/im.png'.vibrate:true
});

setTimeout(() = >n.close(),1000);// Turn off notifications
Copy the code

Notifications can also be interacted through four lifecycle methods that add callbacks

n.onshow=() = >console.log('is onshow');
n.onclick
n.onclose
n.onerror
Copy the code

Page Visibility API

The behavior, minimization, and hiding of the user’s page provide the developer with information about whether the page is visible to the user

Document. visibilityState values :hidden, Visible, prerender VisiBilityChange event, hidden <=> visible, triggeredCopy the code

Streams API

It’s still experimental, there’s no universal browser support

How does the Web consume ordered chunks of information rather than large ones? Support for reading, writing, and processing data in new ways

  • Large chunks of data may not be used all at once, such as a response to a network request. Network load is delivered as a continuous packet of information. Streaming processing allows applications to be used as soon as the data arrives, rather than waiting until all the data is loaded
  • Large chunks of data need to be divided and processed. Video processing, data compression, image coding, JSON parsing

Timing API

A reliable tool for measuring the time it takes for data to and from the browser. The interface is exposed on window.performance

window.performance.now()
Copy the code

The browser performance information focuses on Performance

Web Cryptography API

Cryptography tools, how JavaScript implements encryption in a secure and conventionally consistent way. Generate, use and apply encryption key pairs, encrypt and decrypt messages, reliably generate random numbers