1. Atomics vs. SharedArrayBuffer

2, cross the following news

  • The ability to transfer information across document messages (XDM) across execution contexts.
  • postMessage()Method communication.
    • Three arguments: a message, a string representing the receiving source, and an array of optional transportable objects.
    • The string representing the receiving source is important for security, limiting the target to which the data is delivered.
  • The Window object fires when an XDM message is receivedmessageEvent, which is triggered asynchronously.
    • The event object for the event contains
      • data: is passed to as the first argumentpostMessage()String data of
      • origin: Indicates the source of the document that sends the message
      • source: Window object proxy in the document that sends the message. Used to execute the postMessage() method in the window from which the previous message was sent
  • It is important to verify the source of the sending window to ensure that data is not accidentally sent to an unknown page.

3, Encoding API

  • Used for string and qualitative array conversion

  • TextEncoder, TextEncoderStream, TextDecoder, TextDecoderStream

1. Text encoding

1. Batch coding

const textEncoder = new TextEncoder()
const decodedText = 'foo'
const encodedText = textEncoder.encode(decodedText)
Copy the code
  • encodeInto()
    • Receives a string and the target Unit8Array
    • Returns a dictionary containing read and written properties
    • Represents how many characters were successfully read from the source string and how many characters were successfully written to the target array.
    • When space runs out, the code terminates prematurely, and the dictionary returned reflects this result.

2. Stream coding

  • TextEncoderStreamIn fact, isTransformStreamIn the form ofTextEncoder
  • The decoded text is streamed through a pipe into the stream encoder to produce a stream of encoded text blocks.

2. Text decoding

1, batch decoding

const textDecoder = new Textdecoder()
const encodedText = Unit8Array.of(102.111.111)
const decodedText = textDecoder.decode(encodedText)
Copy the code

2. Stream decoding

File API and Blob API

  • The goal is to be able to access files on the client machine in a secure way.

1. File type

  • Adds the ability to directly access file information based on the file input field in the form.

  • Adds a files collection for the file input element. When the user selects one or more files in the File field, the files collection contains a set of File objects representing the selected files.

    • name: Indicates the file name in the local system
    • size: File size in bytes
    • type: a string containing the MIME type of the file
    • lastModifiedDate: indicates the last modified event of the file
    let filesList = document.getElementById("files-list");
    filesList.addEventListener("change".(event) = > {
      let files = event.target.files,
        i = 0,
        len = files.length;
      while (i < len) {
        const f = files[i];
        console.log(`${f.name} (${f.type}.${f.size} bytes)`); i++; }});Copy the code

2. FileReader type

  • FileReader is similar to XMLHttpRequest, but reads files from the file system instead of data from the server.

    • readAsText(file, encoding): Reads the plain text content from the file and saves it in the Result property. The second parameter represents the encoding, which is optional.
    • readAsDataURL(file): Reads the file and stores the content’s data URI in the Result property.
    • readAsBinaryString(file): Reads the file and stores the binary data for each character in the Result property.
    • readAsArrayBuffer(file): Reads the file and stores the contents of the file as an ArrayBuffer in the Result property.
  • The reading is asynchronous, with each FileReader publishing several events,

    • progress
      • There’s more data
      • It fires every 50 milliseconds and has the same information as XHR’s Progress
        • lengthComputable
        • loaded
        • total
      • You can read the Result property of FileReader even if it doesn’t contain all the data
    • error
      • An error was sent, which is triggered when the file cannot be read for some reason
      • The error attribute of FileReader contains error information
        • Property is an object whose code property represents the error code
          • 1 No file found
          • 2 Security Error
          • 3 The read is interrupted
          • 4 The file is unreadable
          • 5 Coding Error
    • load
      • Triggered after reading is complete
      • If an error event is raised, no load is raised
    let filesList = document.getElementById("files-list");
    filesList.addEventListener("change".(event) = > {
      let info = "",
        output = document.getElementById("output"),
        progress = document.getElementById("progress"),
        files = event.target.files,
        type = "default",
        reader = new FileReader();
      if (/image/.test(files[0].type)) {
        reader.readAsDataURL(files[0]);
        type = "image";
      } else {
        reader.readAsText(files[0]);
        type = "text";
      }
      reader.onerror = function () {
        output.innerHTML = "Could not read file, error code is " +
          reader.error.code;
      };
    
      reader.onprogress = function (event) {
        if (event.lengthComputable) {
          progress.innerHTML = `${event.loaded}/${event.total}`; }}; reader.onload =function () {
        let html = "";
        switch (type) {
          case "image":
            html = `<img src="${reader.result}"> `;
            break;
          case "text":
            html = reader.result;
            break;
        }
        output.innerHTML = html;
      };
    });
    Copy the code
  • Abort () is called to prematurely end the file read, triggering the ABORT event

  • After the load, error, and ABORT events are triggered, the LoadEnd event is also triggered to indicate that all read operations have ended

FileReaderSync type

  • The synchronized version of FileReader does not continue until the entire file has been loaded into memory.
  • It is available only in worker threads, and if it takes too long to read the file it will affect the whole world.
// worker.js
self.omessage = (messageEvent) = > {
  const syncReader = new FileReaderSync();
  console.log(syncReader); // FileReaderSync {}
 
  Block the worker thread while reading a file
  const result = syncReader.readAsDataUrl(messageEvent.data);
  
  // Sample response to a PDF file
  console.log(result); // data:application/pdf; base64,JVBERi0xLjQK...
  
  // Send the URL back
  self.postMessage(result);
};
Copy the code

Blob and partial read

  • The File objectslice()Method to read part of the file
    • Two parameters are received: the start byte and the number of bytes to read.
    • Returns an instance of Blob, which is actually a superclass of File.
  • Blob stands for binary large object and is an encapsulation type of unmodifiable binary data.
  • Arrays containing strings, ArrayBuffers, ArrayBufferViews, and other BLOBs can create bloBs.
  • The Blob constructor takes an options argument specifying the MIME type:
new Blob(['foo']) 
// {size: 3, type: ""}

new Blob(['{"a": "b"}'] and {type: 'application/json'}) 
// {size: 10, type: "application/json"}

new Blob(['<p>Foo</p>'.'<p>Bar</p>'] and {type: 'text/html'}) 
// {size: 20, type: "text/html"}
Copy the code
  • Blob objects have a slice() method to further slice the data.
  • You can also use FileReader to read data from Bolb

Object URLS and bloBs

  • Also known as a Blob URL, it refers to the URL of the data stored in a File or Blob.
  • The advantage is that you can use a file without having to read its contents into JavaScript. Just provide the object URL in the appropriate place.
  • Create method:window.URL.createObjectURL()
    • Pass in a File or Blob object.
    • Returns a string pointing to an address in memory.
  • Removal method:window.URL.revokeObjectURL()

6. Read drag and drop files

  • The triggerdropEvents.
  • throughevent.dataTransfer.filesRead a File that holds a set of File objects.
  • You must cancel the default behavior for Dropenter, Dropover, and DROP.

5. Media elements

  • <audio>,<video>
    • posterThe default image
    • controlscontrol

1, properties,

  • autoplayAutomatically play
  • bufferedThe time range of the downloaded buffer
  • bufferedBytesThe byte range of the downloaded buffer
  • bufferingRateAverage number of bits downloaded per second
  • bufferingThrottledIndicates whether the buffer is intercepted by the browser
  • controlsShow/hide built-in controls
  • currentLoopThe number of times the media has been played
  • currentSrcURL of the current playing media
  • currentTimeNumber of seconds that have been played
  • defaultPlaybackRateGets or sets the default playback rate. The default of 1.0 seconds
  • durationThe total number of seconds of media
  • endedWhether media playback is complete
  • loopGets or sets whether the media loops
  • mutedGets or sets whether the media is muted
  • networkStateCurrent network connection state 0 null 1 Loading 2 loading metadata 3 loading the first frame 4 loading complete
  • pausedIndicates whether the player is paused
  • playbackRateGets or sets the current playback rate
  • playedThe time range that has been played so far
  • readyStateMedia ready 0 unavailable 1 available to display current frame 2 Media available to start 3 Media available to play from start to finish
  • seekableThe range of events to jump to
  • seekingWhether the media is moving to the new location of the media file
  • srcMedia sources
  • startGets or sets the location, in seconds, of a media file from which to start playing
  • totalBytesTotal number of bytes required by the resource
  • videoHeightHeight of video
  • videoWidthVideo width
  • volumeGets or sets the current volume 0.0-1.0

2, events,

  • abortDownload interrupted
  • canplayPlayback can start with readyState of 2
  • canplaythroughPlayback can be played continuously. ReadyState is 3
  • canshowcurrentframeThe readyState of the current frame is 1
  • dataunavailableCannot play without data readyState is 0
  • durationchangeThe duratino property value changed
  • emptiedThe Internet connection is down
  • emptyAn error occurred blocking media downloads
  • endedThe media has played once and stopped.
  • errorA network error occurred during the download
  • loadeddataMedia frame 1 has been downloaded
  • loadedmetadataMedia metadata has been downloaded
  • loadstartDownload has begun
  • pausesuspended
  • playA start playback request was received
  • playingIt’s actually already playing.
  • progressIn the download
  • ratechangeThe media playback rate changes
  • seekedThe jump has ended.
  • seekingPlayback has been moved to a new location
  • stalledThe browser tried to download but did not receive data
  • timeupdatePlay position change
  • volumechangeChange of volume or energy-intensive
  • waitingPause to download more data

3. Custom media player

4. Detect codecs

  • canPlayType()
    • Return probably, maybe, or an empty string

5. Audio type

  • Creating a new instance of Audio starts downloading the specified file, which can then be played by calling Play ()

6. Native drag and drop

  • It can be across panes, across browser containers, and even across applications.

1. Drag and drop events

  • Triggered when an element is dragged
    • dragstart
    • drag
    • dragend
  • Triggers when you drag the element to a valid drop target
    • dragenter
    • dragover
    • Dragleave or drop

2. Customize the placement target

  • By overwriting the default behavior for dragenter and dragover events, you can turn it into an effective prevention target

DataTransfer object

  • The dataTransfer object on the Event object

    • Used to pass string data from the dragged element to the placed target.

    • GetData () gets the value stored by setData()

    • The first argument to setData() and the only argument to getData() are strings representing the data type to be set, text/URL

  • Drag text from a text box, and the browser will call setData() to store the dragged text as text. Similarly, drag a link or image, and store it as a URL, and put it on the target to getData from getData().

  • Text is not treated differently; links placed in another browser window will navigate to this URL

4. DropEffect and Effectalhoward

  • Other properties of the dataTransfer object

  • The dropEffect property tells the browser which placement behavior is allowed

    • noneI can’t put it here
    • moveShould move to the placement target
    • copyIt should be copied to the placement target
    • linkThe drop target navigates to the dragged element
  • DropEffect is useful only after the Effectalhoward property is set, indicating that dropEffect must be set before the dragstart event for the dragged element

    • uninitializedNo action is set for the dragged element
    • noneNo operations allowed
    • copy Only copy dropEffect is allowed
    • linkOnly dropEffect like Lin K is allowed
    • moveOnly move dropEffect is allowed
    • copyLinkDropEffect allows copy and link
    • copyMoveAllows copy and move dropEffect
    • linkMoveAllow dropEffect like Link and move
    • allAll dropEffect is allowed

5. Drag ability

  • draggableProperty indicating whether the element can be dragged

6. Other members

  • dataTransferObject
    • addElement(element)Adds elements for drag operations to transfer data without affecting the appearance of the operation.
    • clearData(format)Clears data stored in a specific format
    • setDragImage(element, x, y)Allows you to specify the picture that appears under the cursor when dragging
    • typesA list of data types currently stored

7, the Notifications API

1. Notification permission

  • Notifications can only be triggered in code running in a security context
  • Notifications must be explicitly approved by the user on a per-source basis
Notification.requestPermission()
  .then((permission) = > {
    console.log('User responded to permission request:', permission);
  });
Copy the code
  • Granted indicates authorization. ‘Denied’ means no.

2. Show and hide notifications

  • new Notification('Title text! ')

  • The returned Notification object calls the close() method to turn off the Notification

3. Notify lifecycle callbacks

  • onshowTriggered when a notification is displayed
  • onclickTriggered when the notification is clicked
  • oncloseFired when the notification disappears or is closed by close()
  • onerrorTriggered when an error occurs preventing notification display

8, Page Visibility API

  • document.visibilityState
    • Represents the following four states
      • The page is in the background TAB or minimized
      • The page is in the foreground TAB
      • The actual page is hidden, but a preview of the page is visible
      • The page is pre-rendered off-screen
    • Possible values: hidden/Visible/PRERender
  • visibilitychangeThe event is raised when the document switch is visible
  • document.hiddenIndicates whether the page is hidden

9, Streams API

  • Solve Web applications that orderly consume small chunks of information instead of large chunks.
    • Chunks of information may not be available all at once.
    • Large pieces of data may need to be processed in smaller pieces

1. Understand flow

  • The Stream API defines three kinds of streams
    • Readable stream: A stream that reads a block of data through a public interface. Internally, data enters the stream from the underlying source and is then processed by the consumer.
    • Writable stream: A stream in which blocks of data can be written to a public interface. The producer writes data to the stream, and the data is passed internally to the underlying data slot (sink)
    • Conversion flow: Consists of two streams, writable for receiving data (writable) and readable for output data (readable). Between the two flows are converters that can examine and modify the contents of the flow as needed.
  • Block, internal queue, and backpressure
    • The basic unit of flow is a block. A block is an arbitrary data structure, usually a stereotyped array
    • Each block is a discrete stream fragment that can be treated as a whole.
    • Blocks are not of fixed size and do not necessarily arrive at fixed intervals.
    • In an ideal flow, the blocks are usually approximately the same size and the arrival intervals are approximately the same.
    • Due to different data in and out rates, mismatches may occur, and flow balance may occur:
      • The flow outlet processes data faster than the flow outlet provides, and the flow outlet is often idle, wasting memory or computing resources.
      • The inflow and outflow are balanced, ideally.
      • The inflow port provides data faster than the flow outlet processes data. This imbalance is a fixed problem, there is bound to be a backlog of data somewhere, and the flow must be processed accordingly.
    • The block entry speed is faster than the exit speed, and the internal queue will continue to grow. Backpressure will be used to inform the inflow that it will stop sending data until it drops below a certain threshold, the high water line.

2. Readable streams

1, ReadableStreamDeafaultController

async function* ints() {
  for(let i = 0; i < 5; i++) {
    yield await new Promise((resolve) = > setTimeout(resolve, 100, i))
  }
}
// enqueue() passes the value to the controller close() closes the stream
const readableStream = new ReadableStream({
  async start(controller) {
    for await (let chunk of ints()) {
      controller.enqueue(chunk)
    }
    controller.close()
  }
})
Copy the code

2, ReadableStreamDeafultReader

  • Through the flow ofgetReader()Method to obtainReadableStreamDeafultReaderThe instance
  • Calling this method acquires the lock on the stream, ensuring that only the reader can read values from the stream.
. readableStream.locked// fasle
const readableStreamDeafultReader = readableStream.getReader()
readableStream.locked // true
Copy the code
  • The consumer uses this reader instanceread()Method can read out values
./ / consumer
(async function() {
  while(true) {
    const {done, value} = await readableStreamDeafultReader.read()
    if(done) {
      break
    }else {
      console.log(value)
    }
  }
})()
Copy the code

3. Writable streams

  • A writable stream is an encapsulation of the underlying data slot, which processes data written through the common interface of the stream

Create WritableStream

  • Through the writable stream public interface can write into the stream, in the passWritableStreamConstructor in the underlyingSink argument, through the implementationwrite()To get the data being written
async function* ints() {
  for(let i = 0; i < 5; i++) {
    yield await new Promise((resolve) = > setTimeout(resolve, 100, i))
  }
}

const wirtableStream = new WritableStream({
  write(value) {
    console.log(value)
  }
})
Copy the code

2, WritableStreamDefaultWriter

  • To write data to a stream, you can use thegetWriter()Methods to obtainWritableStreamDefaultWriterInstance, which acquires a lock on the stream and ensures that only one writer can write data to the stream,
. writableStream.locked// false
const writableStreamDefaultWriter = wirtableStream.getWriter()
writableStream.locked // true
Copy the code
  • Before writing data to the stream, the producer must ensure that the writer can receive the value.
  • writableStreamDefaultWriter.readyReturns a date that is resolved when data can be written to the stream.
  • And then you can pass the value towritableStreamDefaultWriter.write()Methods. Can be called after data has been writtenwritableStreamDeafultWriter.close()Close the stream
./ / producer
(async function() {
  for await (let chunk of ints()) {
    await writableStreamDeafultWriter.ready
    writableStreamDeafultWriter.write(chunk)
  }
  writableStreamDeafultWriter.close()
})()
Copy the code

4. Transform the flow

  • Used to combine readable and writable streams. Blocks of data are converted between two streams bytransform()To complete the
async function* ints() {
  for(let i = 0; i < 5; i++) {
    yield await new Promise((resolve) = > setTimeout(resolve, 100, i))
  }
}

const {writable, readable} = new TransformStream({
  transform(chunk, controller) {
    controller.enqueue(chunk * 2)}})const readableStreamDefaultReader = readable.getReader()
const writableStreamDefaultWriter = writable.getWriter()

/ / consumerasync function() {
  while(true) {
    const {done, value} = await readableStreamDeafultReader.read()
    if(done) {
      break;
    }else {
      console.log(value)
    }
  }
})()

/ / producer
(async function() {
  for await (let chunk of ints()) {
    await writableStreamDefaultWriter.ready
    writableStreamDefaultWriter.write(chunk)
  }
  writableStreamDefaultWriter.close()
})()
Copy the code

5. Connect the flow through pipes

  • Streams can be piped together in a string,pipeThrough()The ReadableStream method connects to TransformStream.
async function* ints() {
  for(let i = 0; i < 5; i++) {
    yield await new Promise((resolve) = > setTimeout(resolve, 100, i))
  }
}

const integerStream = new ReadableStream({
  async start(controller) {
    for await (let chunk of ints()) {
      controller.enqueue(chunk)
    }
    controller.close()
  }
})

const doublingStream = new TransformStream({
  transform(chunk, controller) {
    controller.enqueue(chunk * 2)}})// Connect the stream through a pipe
const pipedStream = integerStream.pipeThrough(doublingStream)

// Get the reader from the output of the connected stream
const pipedStreamDeafaultReader = pipedStream.getReader()

/ / consumer
(async function() {
  while(true) {
    const {done, value} = await pipedStreamDeafaultReader.read()
    
    if(done) {
      break
    }else {
      console.log(value)
    }
  }
})()
Copy the code
  • pipeTo()You can also connect ReadableStream to WritableStream
async function* ints() {
  for(let i = 0; i < 5; i++) {
    yield await new Promise((resolve) = > setTimeout(resolve, 100, i))
  }
}

const integerStream = new ReadableStream({
  async start(controller) {
    for await (let chunk of ints()) {
      controller.enqueue(chunk)
    }
    controller.close()
  }
})

const writableStream = new WritableStream({
  write(value) {
    console.log(value)
  }
})

const pipedStream = integetStream.pipeTo(writableStram)
Copy the code
  • Here the pipe connection operation implicitly obtains a reader from ReadableStream and populates the resulting value into the WritableStream

Timing API

1. High Resolution Time API

  • Date.now() an operation that does not require timing accuracy

    const t0 = Date.now()
    foo()
    const t1 = Date.now()
    const duration = t1 - t0
    conosle.log(duration)
    Copy the code
    • Doration is 0, because date.now () is milliseconds, or 0 if the operation is fast enough
    • Duration is a negative value or a maximum value that can be caused if the system time is adjusted when the operation is performed.
  • Accurately measure the elapsed event window.performance.now(), returning a floating point value with microsecond precision

    • Using relative metrics, timing starts from 0 when context creation is performed.
    • Direct comparisons between different contexts are not possible without shared reference points
  • The performance. TimeOrigin property returns the value of the global system clock when the timer is initialized

2. Performance Timeline API

  • Tools for measuring client latency extend the Performance interface.
  • The browser will automatically log various PerformanceEntry objects, usingperformance.mark()Custom PerformanceEntry objects can be logged.
  • All performance items recorded in an execution context can passperformance.getEntries()To obtain
  • The collection returned represents the browser’s performance timeline. Each object has name, entryType, startTime, and Duration attributes

1. User Timeing API

  • Used to record and analyze custom performance itemsperformance.mark()
  • performance.getEntriesByType('mark')[0]
  • Create a custom performance entry before and after the calculation to calculate the time difference, and the latest token is pushed to the beginning of the array returned by getEntriesByType.
  • Used to generate performance measurement entries, usingperformance.measure()
    • Parameters: Name, startMark, endMark

Navigation Timing API

  • Used to measure the loading speed of the current page. The browser automatically logs this entry when a navigation event occurs

3. Resource Timing API

  • It measures the speed at which resources are being requested while the current page is loading. The browser automatically records resources as they are being loaded.

11. Web Components

1. HTML template

  • There is no mechanism for building a DOM subtree based on HTML parsing and then rendering the tree when needed.
  • The indirect innerHTML method converts the tag string into a DOM element, which is a security risk.
  • Another way to use itdocument.createElement()Creating each element, and then adding it to the orphan root one by one, is cumbersome.
  • A better approach is to write out special tags in advance on the page and have the browser automatically parse them into a DOM subtree.
<template id="foo">
	<p>I'm inside a template!</p>
</template>
Copy the code

1. Use DocumentFragment

  • The text above is not rendered because the contents of

  • A reference to this DocumentFragment can be obtained via the content attribute of the

  • DocumentFragment is an efficient tool for adding elements to HTML in batches, allowing you to add all child nodes at once with at most one layout rearrangement.

  • document.createDocumentFragment()

  • The DocumentFragment will also become empty after the transfer.

2. Use the <template> tag

const fooElement = document.querySelector('#foo');
const barTemplate = document.querySelector('#bar');
const barFragment = barTemplate.content;
console.log(document.body.innerHTML);
// <div id="foo">
// </div>
// <template id="bar">
// 

//

//

// </template> fooElement.appendChild(barFragment); console.log(document.body.innerHTML); // <div id="foo"> //

//

//

// </div> // <tempate id="bar"></template> Copy the code
  • You can useimportNode()Cloning DocumentFragment

3. Template script

  • Script execution can be deferred until the DocumentFragment content is actually added to the DOM tree.

Shadow DOM

  • An entire DOM tree can be added as a node to the parent DOM tree. DOM encapsulation can be implemented, and CSS styles and CSS selectors can be limited to shadow DOM subtrees rather than the entire top-level DOM tree.
  • The shadow DOM actually renders to the page, whereas the HTML template does not

1. Understand shadow DOM

  • Limit CSS to the DOM that uses them

2. Create shadow DOM

  • Not all elements can contain a shadow DOM.

  • Created and added to a valid HTML element with attachShadow(). The element that holds the shadow DOM is called the shadow host. The root node of the shadow DOM is called the shadow root

  • AttachShadow () requires a shadowRootInit object that returns the shadow DOM instance.

    • ShadowRootInit contains the mode property with a value of open or Closed
      • A reference to the open shadow DOM can be obtained on an HTML element using the shadowRoot attribute
      • References to the closed shadow DOM cannot be obtained this way
  • Generally there is little need to create secret shadow DOM scenes.

3. Use shadow DOM

  • Once created, the shadow DOM can be used just like a regular DOM.
for (let color of ['red'.'green'.'blue']) {
  const div = document.createElement('div');
  const shadowDOM = div.attachShadow({
    mode: 'open'
  });
  document.body.appendChild(div);
  shadowDOM.innerHTML = `
    <p>Make me ${color}</p>
    <style>
      p {
        color: ${color};
        }
    </style>
  `;
}
Copy the code
  • The shadow DOM is not monolithic, and HTML elements can move between DOM trees without limit.

4. Composite and shadow DOM slots

  • As soon as the shadow DOM is added to the element, the browser gives it the highest priority, rendering its content over the original text.
  • In order to display text content, use<slot>The tag tells the browser where to place the original HTML.
document.body.innerHTML = ` 
      

Foo

`
; document.querySelector('div') .attachShadow({ mode: 'open' }) .innerHTML = `
`
Copy the code
  • The content is projected as if it existed in the shadow DOM itself. Check the page and you’ll find that the original content has been replaced by teens<slot>
  • The page sees content in the shadow DOM, but it’s really just a projection of the DOM content; the actual elements are still in the outer DOM.
  • In addition to the default slot, you can implement multiple casts using named slots
document.body.innerHTML = ` 
      

Foo

Bar

`
; document.querySelector('div') .attachShadow({ mode: 'open' }) .innerHTML = ` `; // Renders: // Bar // Foo Copy the code

5. Event redirection

  • If a browser event occurs in the shadow DOM, you need a way for the parent DOM to handle the event. Events escape from the shadow DOM and are processed externally through event redirection.
// Create an element as a shadow host
document.body.innerHTML = `
<div onclick="console.log('Handled outside:', event.target)"></div>
`;
// Add a shadow DOM and insert HTML into it
document.querySelector('div')
 .attachShadow({ mode: 'open' })
 .innerHTML = `
<button onclick="console.log('Handled inside:', event.target)">Foo</button>
`;
// When the button is clicked:
// Handled inside: 
// Handled outside: 
      
Copy the code

3. Custom elements

1. Create custom elements

  • The default will be an HTMLElement instance

  • CreateElements. Define () creates a custom element

    class FooElement extends HTMLElement {}
    createElements.define('x-foo', FooElement)
    Copy the code
  • If you inherit from an element class, you can specify the tag as a custom element using the IS attribute and extends option

    class FooElement extends HTMLDivElement {
      constructor() {
        super(a)console.log('x-foo')
      }
    }
    createElements.define('x-foo', FooElement)
    document.body.innerHTML = `
    <div is="x-foo"></div>
    <div is="x-foo"></div>
    <div is="x-foo"></div>
    `
    // x-foo
    // x-foo
    // x-foo
    Copy the code

2. Add the content of the Web component

  • You can add a shadow DOM to the constructor

3. Use custom element lifecycle methods

  • constructor()Called when an element instance is created or when an existing DOM element is upgraded to a custom element
  • connectedCallback()Called each time the custom element instance is added to the DOM
  • disconnectedCallback()Called each time the custom element instance is removed from the DOM
  • attributeChangedCallback()Called every time the value of an observable property changes
  • adoptedCallback()Through thedocument.adoptNode()Called when a custom element instance is moved to a new document object.

4. Reflect custom element attributes

  • Use the get and set functions
  • useobservedAttribute()The get function is called every time the property value changesattributeChangedCallback()

5. Upgrade custom elements

  • customElements.get()Returns the class of the corresponding custom element
  • customElements.whenDefined()Returns a term, resolved when defined
  • customElements.upgrade()Forced to upgrade

12, Web Cryprography API

  • A set of cryptography tools that includes generating, using, and applying encryption key pairs, encrypting and decrypting information, and reliably generating random numbers

1. Generate random numbers

  • Math.random() is a pseudorandom number that simulates random properties and has a fixed algorithm. Not suitable for encrypted computing

  • Cryptography security pseudo-random number generator

    • An additional entropy is added as input, such as testing for hardware events or other system features with unpredictable behavior.
    • The computation speed is obviously slow. But hard to predict, suitable for encryption.
  • Cypto.getrandomvalues () passes random values as arguments to its stereotype array.

    const array = new Uint8Array(1);
    
    for (let i=0; i<5; ++i) {
     console.log(crypto.getRandomValues(array));
    }
    // Uint8Array [41]
    // Uint8Array [250]
    // Uint8Array [51]
    // Uint8Array [129]
    // Uint8Array [35] 
    Copy the code
  • Generates a maximum of 2 ** 16 bytes

  • Reimplement math.random ()

    function randomFloat() {
      const fooArray = new Unit32Array(1)
      const maxUnit32 = 0xFFFFFFFF;
      return crypto.getRandomValues(fooArray)[0] / maxUnit32
    }
    Copy the code

2. Use SubtleCrypto objects

  • window.crypto.subtleAccess, can only be used in HTTPS mode

1. Generate a cryptographic abstract

  • Sha-1: similar to MD5, sha-1 generates 160-bit message hashes after receiving input of any size.

  • Sha-2: A set of hash functions on top of the same crash-resistant unidirectional compression functions, SHA-256, SHA-384, SHA-512, safe.

  • Subtlecrypto.digest () is used to generate a message digest

CryptoKey and algorithms

  • CryptoKey supports a variety of encryption algorithms, allowing control of key extraction and use
    • RSA: public key cryptosystem that uses two prime numbers to obtain a pair of public and private keys.
    • .

3. Generate CryptoKey

  • SubtleCrypto.generateKey()Generate a random CryptoKey.
  • This method needs to be passed in when used
    • A parameter object that specifies the target algorithm
      • RSA RsaHashedKeyGenParams
      • ECC EcKeyGenParams
      • HMAC HmacGenParams
      • AES AesKeyGenParams
    • A Boolean value indicating whether the key can be extracted from a CryptoKey object
    • An array of strings representing which SubtleCrypto method the key is used with
      • Encrypt, Decrypt, sign, verify, deriveKey, deriveBits, wrapKey, and unwrapKey

4. Export and import keys

  • exportKey()And make the target format (RAW, PKCS8, SPKI or JWK) can obtain the key
  • importKey()Is with theexportKey()Reverse operation

5. Derive the key from the master key

  • Obtain a new key from an existing key through configurable properties

  • DeriveKey () returns a contract resolved as a CryptoKey

  • DeriveBits () returns a period resolved to an ArrayBuffer

Use asymmetric keys to sign and authenticate messages

  • SubtleCrypto.sign()Signature Private key signature
  • SubtleCrypto.verify()Verifying public key Authentication

7. Use symmetric key encryption and decryption

  • SubtleCrypto.encrypt()encryption
  • SubtleCrypto.decrypt()decryption

8. Packaging and unpacking key

  • SubtleCrypto.wrapKey()packaging
  • SubtleCrypto.unwrapKey()Unpack the