Processes and threads

  1. Processes and threads
  • Process:

The basic unit in which concurrent programs allocate and manage resources during execution. It is a dynamic concept that competes with the basic unit of computer system resources

  • Thread:

Is an execution unit of a process and a process internal scheduling entity. A basic unit smaller than a process that runs independently. Threads are also called lightweight processes.

In summary:

An application that runs in memory. Each process has its own independent memory space. A process can have multiple threads. For example, in Windows, a running XX. exe is a process.

An execution task (control unit) in a process that is responsible for the execution of programs in the current process. A process has at least one thread. A process can run multiple threads, and multiple threads can share data.

  1. Five processes in the browser

Browser load resource mechanism

The browser opens up a GUI rendering thread that executes the code from top to bottom, dedicated to rendering the rendered page.

  • Browser process: responsible for page display, user interaction, child process management, storage, etc
  • Render process: Each page has a separate render process, with the core used to render the page
  • Network process: mainly handle network resources loading (HTML, CSS, JS, etc.)
  • GPU process: 3D drawing, improve performance
  • Plugin processes: Plugins installed in Chrome

What happens from entering the URL to displaying the page in the browser

The keyword or URL the user entered? If it is a keyword, use the default engine to produce the URL

  1. Browser processes call each other
  • Enter the URL in your browser to start navigation. Prepare the render process
  • The request is sent in the network process and the result of the response is sent to the renderer first
  • Parse the page and load the required resources in the page
  • After rendering and showing the results, we started to refine each step of the process and extract the benefits from the process that we could optimize
  1. URL Request process

Network seven – layer model: object, number, network, transmission, meeting, table, response

TCP is safe and reliable, UDP will lose packets, but the speed is faster. (will, table, should)

  • The browser checks whether the current URL is cached and whether the cache has expired. Returns the contents of the cache directly
  • Check whether the domain name has been resolved. If no, perform DNS resolution to resolve the domain name to an IP address (DNS based on UDP) IP + end number + host
  • The request is HTTPS for SSL negotiation
  • If IP addresses are used for addressing, up to six HTTP requests can be queued
  • After queuing, the server creates a TCP link for transport (three-way handshake)
  • The TCP protocol is used to separate large files into packets for transmission. (The packets are separated into sequential packets.) Reliable and orderly, the server rearranges packets in sequence
  • Sending an HTTP request (request line, request header, request body)
  • The keep-alive attribute is supported in HTTP1.1. TCP connections are not closed immediately, and subsequent requests save the cost of establishing a link
  • The server responds to the data (response line, response header, response body)
  • The server returns 301 302 and the browser redirects (recaching)
  • Server 304 queries browser cache and returns (server can set mandatory cache)
  • Observe the request sending process using Network Timing

Queuing Each domain name processes a maximum of six TCP connections. If the number exceeds the number, the requests are queued and the disk space is allocated for a certain period of time
Stalled Wait time before a request is issued (processing broker, link reuse)
DNS lookup Time to find DNS
initial Connection Time of establishing a TCP connection
SSL SSL Handshake Time (SSL negotiation)
Request Sent Request sending time (negligible)
Waiting(TTFB) The time to wait for a response, the time to wait for the first character to return
Content Dowloaded The time used to respond to the download

Performance.getentrirs () is the Performance Timing case used to get all resources on the page

Blue: DOMContentLoaded: the time when the DOM build is complete

Red: Load; All browser resources are loading

  1. HTTP history
  • HTTP 0.9 was responsible for transferring HTML in its earliest days without request headers and response headers
  • HTTP 1.0 provides HTTP headers to handle different resources depending on the header
  • HTTP 1.1 enables keep-alive link reuse piped servers to handle multiple requests (queue blocking) by default
  • HTTP 2.0 uses the same TCP connection to send data a domain name a TCP (multiplexing) header compression server can push data to clients
  • HTTP 3.0 solves the problem of TCP queue header blocking. QUIC uses UDP
  1. Rendering process

  1. Browsers can’t use HTML directly, they need to convert HTML into a DOM tree (document)
  2. Browsers cannot parse plain text CSS styles directly. Instead, they need to parse CSS into styleSheets. CSSOM(document.styleSeets)
  3. Calculate the Attachment for each node in the DOM tree.
  4. Create a render (layout) tree and add visible nodes from the DOM tree to the layout tree. And compute the coordinate position of the node rendering to the page. (layout)
  5. Through the layout tree, layers (based on positioning properties, transparency properties, transform, clip properties, etc.) are created to create the layer tree
  6. The different layers are drawn and handed over to the composition thread to produce the final page, which is displayed in the browser (Painting,Display) to view the list of layers and layers to draw

Layer:

Simulate the request -> render process

Request message format

  • Start line: [method] [space] [request URL] [HTTP version] [newline]
  • Header: [header name] [:] [space] [header content] [newline]
  • End of header: [newline]
  • entity

Response message format

  • Start line: [HTTP version] [space] [status code] [space] [reason phrase] [newline]
  • Header: [header name] [:] space [newline]
  • End of header: [newline]
  • entity
  1. Sends HTTP requests based on TCP
const net = require("net"); class HTTPRequest { constructor(options) { this.method = options.method || "GET"; This. The host = options. The host | | "127.0.0.1"; this.port = options.port || 80; this.path = options.path || "/"; this.headers = options.headers || {}; } send(body) { return new Promise((resolve, reject) => { body = Object.keys(body) .map((key) => `${key}=${encodeURIComponent(body[key])}`) .join("&"); if (body) { this.headers["Content-Length"] = body.length; } const socket = net.createConnection( { host: this.host, port: this.port, }, () => { const rows = []; Rows. Push (` ${. This method} ${enclosing path} HTTP / 1.1 `); Object.keys(this.headers).forEach((key) => { rows.push(`${key}: ${this.headers[key]}`); }); let request = rows.join("\r\n") + "\r\n\r\n" + body; socket.write(request); }); Socket. on("data", function(data) {// data is the result of sending a request}); }); }} Async function Request() {const request = new HTTPRequest({method: "POST", host: "127.0.0.1", port: 3000, path: "/", headers: { name: "zhufeng", age: 11, }, }); Let {responseLine, headers, body} = await request. Send ({address: "Beijing"}); } request();Copy the code
  1. Parsing response results
const parser = new HTTPParser(); Socket. on("data", function(data) {// data is the result returned after sending a request. if (parser.result) { resolve(parser.result); }});Copy the code
  1. Parsing HTML
let stack = [{ type: "document", children: [] }]; const parser = new htmlparser2.Parser({ onopentag(name, attributes) { let parent = stack[stack.length - 1]; let element = { tagName: name, type: "element", children: [], attributes, parent, }; parent.children.push(element); element.parent = parent; stack.push(element); }, ontext(text) { let parent = stack[stack.length - 1]; let textNode = { type: "text", text, }; parent.children.push(textNode); }, onclosetag(tagname) { stack.pop(); }}); parser.end(body);Copy the code
  1. Parsing the CSS
const cssRules = []; const css = require("css"); function parserCss(text) { const ast = css.parse(text); cssRules.push(... ast.stylesheet.rules); } const parser = new htmlparser2.Parser({ onclosetag(tagname) { let parent = stack[stack.length - 1]; if (tagname == "style") { parserCss(parent.children[0].text); } stack.pop(); }});Copy the code
  1. Calculate the style
function computedCss(element) { let attrs = element.attributes; Element.com putedStyle = {}; Object.entries(attrs).foreach (([key, value]) => {cssrules.foreach ((rule) => {let selector = rule-.selectors [0];  if ( (selector == "#" + value && key == "id") || (selector == "." + value && key == "class") ) { rule.declarations.forEach(({ property, value }) => { element.computedStyle[property] = value; }); }}); }); }Copy the code
  1. Layout drawing
Function layout(element) {// Calculate the position -> Draw if (object.keys (element.computedStyle).length! = 0) { let { background, width, height, top, left } = element.computedStyle; let code = ` let canvas = document.getElementById('canvas'); canvas.width = window.innerWidth; canvas.height = window.innerHeight ; let context = canvas.getContext("2d") context.fillStyle = "${background}"; context.fillRect(${top}, ${left}, ${parseInt(width)}, ${parseInt( height )}); `; fs.writeFileSync("./code.js", code); }}Copy the code

Summary: How is the DOM generated

  • If the server returns text/ HTML, the browser will parse the data through HTMLParser (parsing while downloading).
  • Before parsing, the system preloads JS and CSS files
  • Byte streams -> word dividers -> Tokens -> generate nodes based on Tokens -> insert into the DOM tree
  • Encountering JS: If a script tag is encountered during parsing, HTMLParser stops parsing and executes the corresponding script (download).
  • Wait for all CSS loads on the current script to be parsed before executing js.

How many times has the following code been rearranged?

Fourth, network optimization strategy

  • Reduce the number of HTTP requests, merge JS and CSS, and reasonably embed CSS and JS
  • Reasonably set server cache to improve server processing speed. (Mandatory cache, comparison cache)
// Expires/Cache-Control   Etag/if-none-match/last-modified/if-modified-since
Copy the code
  • Avoid redirection, redirection slows response time (301,302)
  • Avoid using style or script tags to import code blocks directly, use external files (this will increase the number of requests, the phone can import style, code blocks).
  • Use dns-prefetch to perform DNS prefetch
  • Avoid empty href and SRC. The reason is that the loading action is still caused during rendering.
  • Domain name sharding is used to store resources under different domain names. A maximum of six TCP connections can be processed in the same domain name.
  • CDN acceleration is used to speed up access. (Assign nearest, highly available)
  • Gzip compression optimization for volume compression of transmitted resources (HTML, JS, CSS)
// Content-Encoding: gzip
Copy the code
  • Load data priority: preload (prerequest resources needed for the current page) Prefetch (resources to be used in the future page) caches data into the HTTP cache
<link rel="preload" href="style.css" as="style" />
Copy the code
  1. Avoid redirects, which take about 600 milliseconds each time.
  2. Use static resource powder fish storage to increase the number of parallel downloads. Again, there is a limit to the number of requests for the browser’s domain resources.
  3. Use CDN content delivery network. CDN can improve the loading speed of static resources.
  4. Using CDN Combo, multiple file requests are packaged into a single file, so that the same HTTP request can be used to speed up the download of resources.
  5. Use Ajax caching: For GET requests, add Expires to the header to cache the response.
  6. Use get requests. The reason is that a POST request sends the header first and then the HTTP body. Get requests send only the header.
  7. Reduce the size of cookies and implement cookie isolation (that is, use different domain names to store static resources, thus isolating cookies); Set the appropriate domain level and validity period.
  8. Reduce the size of favicon.ico and cache it.
  9. Asynchronous JS resources are recommended; Asynchronous JS resources do not block document parsing.
  10. Split CSS and JS resources properly to avoid blocking rendering.
  11. Avoid loading CSS resources in import mode. The reason is that the import mode will not load the specified CSS resource until it is resolved to @import, which will greatly delay the CSS rendering completion time.
  12. Compress resources with Content-encoding: gzip response header. The following is a compressed file based on nginx.
etag on; # Enable eTag expires 7d; # set cache expiration time to 7 days gzip on; # compression resources gzip_types text/plain application/javascriptapplication/x - javascripttext/CSS application/xmCopy the code

Key render paths

Browser rendering process

The browser first parses the HTML into a DOM tree to compute the DOM structure; Then load the CSS to parse into CSSOM; Finally, DOM and CSSOM are combined to generate a layout Tree, and the browser calculates the layout according to the page (rearrangement stage). Finally, the browser paints the page according to the Layout Tree.

javascript–>Style–>Layout–>Paint–>Composite

  • Reflow: Add elements, delete elements, modify the size, move the location of an element, and obtain location information
Rearrangement refers to rearranging elements of a layout tree. Some DOM sizes and positions have changed (the layout and geometry of the page have changed). The process of rerendering the DOM is DOM rearrangement (DOM rearrangement). This is why the virtual DOM was introduced. 1. Stage 2 of the first page layout calculation. Add or remove DOM nodes, change layout tree 3. Element position, element font size, etc. also cause DOM backflow 4. The geometry properties of the node are changed, such as width, height, border, padding,margin, etc. Search for box properties such as offsetWidth, offsetHeight, Client, Scroll, etc. The browser will rearrange operations to get these properties. 6. The V-IF operation in the framework can also cause backflow.Copy the code
  • Repaint: Changes in the style of an element on a page do not affect its position in the document flow.
Redraw is when the style of the page has changed, but the DOM structure/layout has not. If the color changes, the browser will redraw the desired color. 1. Stage 2 of the first page painting. The transform is at the Composite Layer, and the transform is at the left, width, and color of the Composite layer. Elements such as Hight belong to the Layout layer, which has not been re-painted.Copy the code
  • Add and remove elements (Reflux + redraw)
  • Hide elements: display: None (reflux + redraw); Visibility :hidden (redraw only, do not return)
  • Move elements: change top,left (not necessarily causing backflow); Move an element into another parent element (reflux + redraw) and so on
  • < span style = “margin: 0px; padding: 0px; Layout independent properties (redraw only, no reflow). See csstriggers.com/ for more information
  • User actions: Change browser size, change browser font size, etc. (Backflow + redraw)

The difference between:

The rearrangement will cause the DOM structure to change, and the browser will need to rerender the layout to generate the page, but the redrawing will not cause the DOM to change, only the style change, which can be very performance costly.

Principle of rearrangement or redrawing:

  • Webkit renders the elements in the render tree into an object, and each object represents a rectangular area containing a collection of information such as width, height, and position.
  • Objects rendered at the same time will receivedisplayProperties to generate different render objects.

Redraw and backflow should be minimized

  1. Forced synchronization layout problem

JavaScript forces computing style and layout operations to be brought forward to the current task

<div id="app"></div> <script> function reflow() { let el = document.getElementById("app"); let node = document.createElement("h1"); node.innerHTML = "hello"; el.appendChild(node); // Forcibly synchronize layout console.log(app.offsetheight); } requestAnimationFrame(reflow); </script>Copy the code
  1. Layout thrashing

In a piece of JS code, repeated layout operations are called layout jitter

function reflow() { let el = document.getElementById("app"); let node = document.createElement("h1"); node.innerHTML = "hello"; el.appendChild(node); // Forcibly synchronize layout console.log(app.offsetheight); } window.addEventListener("load", function() { for (let i = 0; i < 100; i++) { reflow(); }});Copy the code
  1. Reduce backflow and redraw
  • Out of document flow
  • Add a fixed width and height to the image while rendering
  • Use CSS3 animations whenever possible
  • It can be extracted into a separate layer using will-change
  • Avoid frequent DOM manipulation and use vue/ React instead.
  • Avoid the use oftableLayout, becausetableLayout calculation takes a long time and consumes performance;
  • Style set changes, avoid using style too much, and instead modify class.
  • Separate reads and writes of styles. Set the stylestyleAnd read stylesoffsetEqual separation can also reduce the number of backflow.
  • Design the animation on top of the document flowpositionProperties of theabsolutefixedOn. Use GPU to accelerate synthesis.
  • ClassName or cssText batch update styles to avoid frequent backflow or redraw caused by single-attribute operations
  • Insert the document after styling the newly created element; Or set the display property of the node to None, adjust the style, and then return to the display state
  • A RenderLayer is used for frequently redrawn elements: With video elements, WebGL, Canvas, CSS3 3D, CSS filters, and elements whose Z-index is larger than a neighboring node will have a separate RenderLayer, for example by adding transform: translateZ(0); backface-visibility: hidden; Style is ok.

Examples:

How many times has the following code been rearranged? box.style.width = "100px"; box.style.width = "100px"; box.style.position = "relative"; Copying code you might think is 3 times, but in modern browsers, the browser will create a render queue for the above style code, put all the render code in the queue, and update it last time, so the reordering is 1 time. Box-style. width = "100px"; box-style. width = "100px"; box.style.width = "100px"; box.offsetWidth; box.style.position = "relative"; The answer is 2, because offsetWidth causes the render queue to refresh to get the exact offsetWidth value. Finally, position causes the position of the element to change and triggers a backflow. So there are two total times.Copy the code

Static file optimization

  1. Image optimization

Image format:

  • JPG: suitable for colorful photos and banners; Does not work with graphics, text, ICONS (texture edges are jagged), transparency is not supported
  • PNG: suitable for solid color, transparent, icon, translucent support; Not suitable for colorful pictures, as lossless storage can result in large storage volume
  • GIF: animated, movable icon; Does not support translucency, discomfort and storage of color pictures
  • Webp: suitable for semi-transparent pictures, can ensure the image quality and small volume
  • SVG images: Smaller and more expensive to render than JPG and JPG, suitable for small, monochromatic ICONS;

Picture optimization:

  • Avoid empty SRC images
  • Reduce image size to save user traffic
  • The IMG tag sets the Alt attribute to improve the user experience when an image fails to load
  • Native loading:lazy image loading
<img loading="lazy" src="./images/1.jpg" width="300" height="450" />
Copy the code
  • Load images of different sizes and pixels in different environments
<img
  src="./images/1.jpg"
  sizes="(max-width:500px) 100px,(max-width:600px) 200px"
  srcset="./images/1.jpg 100w, ./images/3.jpg 200w"
/>
Copy the code
  • Consider using progressive images for larger images
  • Base64URL is used to reduce image requests
  • Use Sprite image to merge icon pictures, etc
  1. HTML optimization
  • Semantic HTML: the code is concise and clear, which is conducive to search engines and team development
  • Declare character encoding up front so the browser can quickly determine how to render web content
  • Reduce HTML nesting and DOM nodes
  • Remove unnecessary Spaces, empty lines, comments, and useless attributes
  • HTML reduces iframes (iframes block onLoad events that can load iframes dynamically)
  • Avoid table layouts
  1. CSS optimization
  • Try not to use@importSince @import is loaded serially, it will be blockedGUIRender thread.
  • Fewer pseudo-class selectors, fewer style layers, and fewer wildcards
  • Avoid CSS expressions, which are frequently evaluated and recalculated when scrolling or moving the mouse (IE6,7)
background-color: expression( (new Date()).getHours()%2 ? "red" : "yellow" );
Copy the code
  • Remove empty lines, comments, reduce meaningless units, and CSS compression
  • Using external linked CSS, you can cache CSS
  • Add media fields and load only valid CSS files
<link href="index.css" rel="stylesheet" media="screen and (min-width:1024px)" />
Copy the code
  • The CSS contain property isolates elements
  • Less CSS code can be used inlinestyleTag to reduce requests.
  • To use lesslinkCan reduce the number of HTTP requests.
  • The CSS selector chain is as short as possible because CSS selectors are rendered from right to left.
  • Puts the link request written to<head></head>Internally, resources can be requested from the start and the GUI rendered at the same time.
  1. JS optimization
  • Load files asynchronously via Async, defer

  • Reduce DOM manipulation and cache accessed elements
  • Operations are not applied directly to the DOM, but to the virtual DOM. The last one is applied to the DOM.
  • Use webworker to solve application blocking problems
  • IntersectionObserver
const observer = new IntersectionObserver(function(changes) { changes.forEach(function(element, index) { if (element.intersectionRatio > 0) { observer.unobserve(element.target); element.target.src = element.target.dataset.src; }}); }); function initObserver() { const listItems = document.querySelectorAll("img"); listItems.forEach(function(item) { observer.observe(item); }); } initObserver();Copy the code
  • Virtual scroll vertual-scroll-list
  • RequestAnimationFrame, requestIdleCallback

  • Try not to use eval as it takes too long
  • Reduce the number of event bindings by using event delegates.
  • Use Canvas animation and CSS animation as much as possible

5. Font optimization

@font-face { font-family: "Bmy"; src: url("./HelloQuincy.ttf"); font-display: block; */ /* fallback = fallback = fallback = fallback = fallback = fallback */ /* optional */} body {font: "Bmy"; }Copy the code

FOUT(Flash Of Unstyled Text) waits for a period Of time, and displays the default first if the loading is not complete. Switch after loading. FOIT(Flash Of Invisible Text) font displayed after loading, system font degraded due to loading timeout (white screen)

Vii. Optimization strategy

  • The more critical resources there are, the longer the first page load time will be
  • The size of the key resource, the smaller the content, the shorter the download time
  • Optimized white screen: Inline CSS and JS to remove file downloads, smaller file size
  • Prerender, prerender when packing
  • Using SSR to speed up the first screen loading (consuming server resources) is conducive to SEO optimization. The first screen is rendered on the server side and subsequent interactions are rendered on the client side

Page rendering class

  1. Putting CSS resources at the top of the HTML ensures that the browser finishes rendering the page as soon as possible.
  2. Put the JS resources at the end of the HTML to avoid blocking the page rendering during loading and parsing the JS.
  3. Avoid zooming images directly in HTML. The reason is that the action of zooming in and out of an image causes rearrangement and redrawing.
  4. Reduce the number and depth of DOM nodes to speed up dom tree building.
  5. Avoid slow elements such as tables and iframe. The reason is that the table will wait until its DOM tree is fully generated before being inserted into the page at once. Iframe resources download process will block the parent page static resources download and CSS, DOM tree parsing.
  6. Avoid running time-consuming JS; Resources are preloaded. When the browser is idle, resources (including the resources on the page to which the browser belongs and the resources of the latest version) are preloaded.
  7. Avoid slower-running CSS expressions or filters.

Network loading class

  1. First screen data is requested in advance to avoid requesting data after loading the JS file.
  2. First screen loading and on-demand loading, non-first screen scrolling loading, to minimize the first screen content.
  3. Modular resources are downloaded asynchronously and in parallel, with the help of Webpack to achieve dynamic-import implementation.
  4. Inline first screen necessary CSS and JS to avoid blank pages.
  5. Configure the DNS pre-resolution function for file resources so that the browser can resolve the IP address of the host that obtains static resources in advance, avoiding initiating DNS resolution requests upon request. Such as
<meta http-equiv="x-dns-prefetch-control" content="on" />
<link rel="dns-prefetch" href="//cdn.domain.com" />
Copy the code

The script class

  1. Use id selectors whenever possible. Cause The id element has the highest execution speed.
  2. Try to cache DOM objects to avoid having to look them up from the DOM tree every time you use them.
  3. Use event brokers instead of using event binding directly. This avoids unnecessary memory leaks and event binding issues that require dynamic addition of elements.
  4. Use TouchStart instead of Click. There is a 300-millisecond delay between the touchStart event and the Click event on the mobile side.
  5. Avoid touchmove, Scroll link event processing, event trigger frequently easy to make the page slow, can trigger the event every 16ms (60 frames of the true interval is 16.7ms).
  6. Avoid eval, with, and join instead of +. Es6 template strings are recommended. It’s safer.
  7. Use es6+ features as much as possible. It’s safer and more efficient.

Apply colours to a drawing class

  1. Using viewPort to fix the item rendering, you can load the rendering process while avoiding rearranging and redrawing caused by scaling.
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
Copy the code
  1. Avoid all forms of rearrangement and redrawing.
  2. With CSS3 animation, turn on GPU acceleration with Transform: translateZ(0) to make the animation smoother.
  3. Use more efficient animation implementation methods such as Canvas and requestAnimationFrame reasonably, and avoid setTimeout, setInterval and other methods to directly process continuous animation.
  4. Use SVG instead of images because SVG content is smaller and its structure is easier to adjust.
  5. Avoid time-consuming float layouts. A fixed or elastic layout is recommended.
  6. Avoid excessive font size declarations, which can increase font size calculations.

Architecture Protocol Class

  1. Try using SPDY and http2 protocols. SPDY protocol can reuse connections to speed up the transmission process and shorten the load time of resources.
  2. Use back-end data rendering (data backfilling into HTML) to avoid blank pages and solve mobile SEO problems.
  3. Use Native View instead of DOM to bring page content rendering to a level close to that of a client Native application.

8. Browser storage

  • Cookie: Cookie is valid within the expiration time. The storage size is about 4K and the number of fields is limited. It is not suitable for large amounts of data storage.
  • Setting the cookie validity Period
  • Fewer cookies are transmitted according to different subdomains
  • The static resource domain name and cookie domain name must be different to avoid cookies during static resource access
  • LocalStorage: the maximum storage capacity in chrome is 5M. It exists all the time unless manually cleared. Use localStorage to store static resources
function cacheFile(url) {
  let fileContent = localStorage.getItem(url);
  if (fileContent) {
    eval(fileContent);
  } else {
    let xhr = new XMLHttpRequest();
    xhr.open("GET", url, true);
    xhr.onload = function() {
      let reponseText = xhr.responseText;
      eval(reponseText);
      localStorage.setItem(url, reponseText);
    };
    xhr.send();
  }
}
cacheFile("/index.js");
Copy the code
  • SessionStorage: session-level storage for transferring values between pages
  • IndexDB: Local database for the browser (basically unlimited)
let request = window.indexedDB.open("myDatabase");
request.onsuccess = function(event) {
  let db = event.target.result;
  let ts = db.transaction(["student"], "readwrite");
  ts.objectStore("student").add({ name: "zf" });
  let r = ts.objectStore("student").get(5);
  r.onsuccess = function(e) {
    console.log(e.target.result);
  };
};
request.onupgradeneeded = function(event) {
  let db = event.target.result;
  if (!db.objectStoreNames.contains("student")) {
    let store = db.createObjectStore("student", { autoIncrement: true });
  }
};
Copy the code

Ix. Experience PWA (Progressive Web App)

Webapp has poor user experience (unable to access offline) and low user stickiness (unable to save entry). Pwa aims to solve these problems and make WebApp fast, reliable and safe

  • Web App Manifest: Add websites to the desktop for a more native like experience
  • Service Worker: Offline cache content, with cache API
  • Push Api & Notification Api: Message Push and Notification
  • App Shell & App Skeleton

X. Performance analysis

  1. Performance:

The Performance API can be used to analyze the Performance of a web page rendering process as well as the execution Performance of a method.

  • Performance. Memory: Indicates the memory usage
  • Performance.now () : Gets the time from navigationStart to the current time, which can be used to calculate the execution time of the method
  • Performance. Mark (markName) : Marks the corresponding viewpoint
  • Performance. Measure (name, startMark, endMark) : calculates the execution time of a method
  • Performance. GetEntriesByName (name) : access to specify the measure
  • Performance.clearmarks () : Clears flags
  • Performance. ClearMeasures () : removal of the measure
  1. Profile:

Console.profile () or console.profileend () can be used to analyze the memory and CPU usage of JS scripts. The following code is an example of monitoring the performance of a method using Performance, profile ().

const analyse = (fn, options) => { const { measureName } = options; performance.mark(`${measureName}-start`); console.profile(); fn(); console.profileEnd(); Performance. Mark (' ${measureName}-end '); Measure (measureName, '${measureName}-start', '${measureName}-end',); / / get all the names for mySetTimeout measures const measures = performance. GetEntriesByName (measureName); const measure = measures[0]; console.log(`${measureName} milliseconds: ${measure.duration}`); // Clear the flag performance.clearmarks (); performance.clearMeasures(); }; analyse(() => { for (let i = 0; i < 1000; i++){ console.log(i + 1); }; }, { measureName: 'cycle' });Copy the code