preface

You write front-end, also dare to call yourself a programmer??

Those of you who believe in web front-end development will, nine times out of ten, be subjected to this kind of skepticism or ridicule along the way (most of which are meant to be). Write a few tags, know some HTML CSS is a programmer? Do you know CPU, storage, networking, clustering? Do you understand concurrency, business architecture, databases, performance tuning, distributed computing, cluster architecture, disaster recovery, security, operations

Hum spicy chicken 👎

Today we bring salt for the front end

In recent years, Web applications in the entire software and Internet industry bear more and more responsibility, software complexity and maintenance costs are getting higher and higher, Web technology, especially Web client technology, ushered in the explosive development.

  • 1. Use Node to make front-end engineering scheme of the middle layer
  • 2. Packaging tools such as Webpack and Rollup; Translation tools like Babel and PostCSS
  • React, Angular, Vue, and other front-end frameworks for modern Web applications and their ecology
  • 4. Hybrid development mode combined with APP, embedded single-page Webview, Hybrid APP

JavaScript computing power, CSS layout capabilities, HTTP caching, and browser apis bring about a qualitative leap in user experience

To enter the theme, we will start from two aspects:

  • Next generation Web applications: PWA
  • WebAssembly

Let’s talk about the trend of front-end development

Next generation Web applications: PWA

As usual, let’s compare the advantages and disadvantages of WebAPP and native APP in daily life

Advantages of Web Apps over native apps
Low development cost
Suitable for a variety of mobile devices, not IOS Android multiple sets of code
Iterative update is easy, eliminating the time loss caused by audit, package issuance and various channel release
No installation cost, ready to use
Disadvantages of Web Apps compared to native apps
The browsing experience is no better than native apps, with slow loading and a blank screen spinning in circles
Very few support offline mode
Message push is extremely difficult
The local system function cannot be called

The emergence of a number of key technologies in PWA finally brings us to the dawn of a complete solution to these two platform-level problems

Problems solved by PWA

  • Can significantly improve the application load speed
  • Even make web applications available in offline environments (Service workers)
  • Web apps can be added to the home screen, full-screen execution (Web App Manifest) just like native apps.
  • Further improve the web application and operating system integration capabilities, so that web applications can initiate Push notifications (API and Notification API) when not activated.

A very mature 🌰 (example) “Alibaba of India” — Flipkart

FlipKart Lite is probably one of the most popular examples of PWA. When the browser detects that a user needs FlipKart Lite, it says, “Hello, you can add it to the home screen,” or manually add it to the top right corner. This way, Flipkart Lite leaves a custom icon on the home screen as an entry point, just like a native app. Instead of adding a Web bookmark, Flipkat Lite opens in full screen when the user clicks on the icon, no longer stuck in the browser UI, and has its own launch screen effect.

In a big breakthrough, Flipkart Lite will perform as a native app when the web is not accessible, and will be black and white, rather than black and white. Moreover, items that have been accessed are cached and can be accessed offline. Flipkart Lite triggers push notifications like a native app to lure users back to the app during price drops and promotions.

Let’s take a look at the two key technology points of PWA, the Web APP Manifest and the Service Worker

Web App Manifest

Refer to the link: https://developers.google.com/web/fundamentals/web-app-manifest/?hl=zh-cn

It is essentially a web app manifest, a JSON file that developers can use to control how web apps or websites are presented to users in areas where they want to see the app (such as the home screen of a mobile device), indicate which features can be enabled, and define how they will look when launched. It is an essential element of PWA technology

To summarize the three steps of Manifest:

  • Create a manifest and link it to your page.
  • Controls what the user sees when booting from the home screen.
  • Splash screen, theme color and open url, etc.

Creating a Manifest Demo

Short_name: Provides a short, readable name for the application. Used when there is not enough space to display the full name. Name: Provides a human-readable name for the application. ICONS: an array of image objects used as application ICONS in various environments start_URL: specifies the URLS loaded when the user launches the application from the device.

After you create the manifest and add it to your site, add the Link tag to all pages that contain the web application

Some options

Add splash Screen

Setting the startup Style

I’m going to go full screen or I’m going to keep the address bar

debugger

The Chrome browser already gives us some tools to add it to your Chrome app by going directly to the Application section, selecting the Manifest TAB.

The MANIFEST in HTML5 is used to cache some resources on a web page, which is completely different from the WebApp Manifest in our PWA

<! DOCTYPE HTML> <html manifest="demo.appcache">
</html>
Copy the code

Service Worker

Our entire Web application was built on the premise that users could access the Internet, so when they were offline, they just went round and round. Many similar attempts have been made by the Web community, such as APP Cache. But it, with almost no routing mechanism, had bugs that could not be monitored and was now killed in HTML5.1

At this time, Service workers come out of nowhere!!

Service Workers essentially act as a proxy server between the Web application and the browser, and can also act as a proxy between the browser and the network when the network is available. They are designed, among other things, to enable the creation of an effective offline experience, intercept network requests and take appropriate action based on whether the network is available and whether updated resources reside on the server. They also allow access to push notifications and background synchronization apis.

The service worker will follow the following life cycle:

  • download
  • The installation
  • The activation

Take a look at the example code


if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/sw-test/sw.js', { scope: '/sw-test/' }).then(function(reg) {

    if(reg.installing) {
      console.log('Service worker installing');
    } else if(reg.waiting) {
      console.log('Service worker installed');
    } else if(reg.active) {
      console.log('Service worker active');
    }

  }).catch(function(error) {
    // registration failed
    console.log('Registration failed with ' + error);
  });
}
Copy the code

This code made a feature to check first, before registration to ensure that the Service Worker is supported, then, we use ServiceWorkerContainer. The register () function to register the Service Worker, This registers a service worker.

self.addEventListener('install'.function(event) {
  event.waitUntil(
    caches.open('v1').then(function(cache) {
      return cache.addAll([
        '/sw-test/'.'/sw-test/index.html'.'/sw-test/style.css'.'/sw-test/app.js'.'/sw-test/image-list.js'.'/sw-test/star-wars-logo.jpg'.'/sw-test/gallery/bountyHunters.jpg'.'/sw-test/gallery/myLittleVader.jpg'.'/sw-test/gallery/snowTroopers.jpg']); })); });Copy the code
  • A new install event listener, then on the event after a ExtendableEvent. WaitUntil () method, this will ensure that the Service Worker not waitUntil in before () code has been completed installation is complete.

  • In waitUntil(), we use the caches.open() method to create a new cache called v1, which will be the first version of our site resource cache.

  • It returns a promise to create a cache, and when it’s resolved, we’ll then call addAll(), a method on the cache example we created, which takes an array of urls relative to Origin, These urls are a list of the resources you want to cache.

  • Service Worker’s new signature storage API – Cache – a global object on a Service Worker that allows us to store resources sent by network responses and generate keys based on their requests.

Refer to the link: https://developer.mozilla.org/zh-CN/docs/Web/API/Service_Worker_API/Using_Service_Workers

Push Push Notification

The emergence of Push API enables Push service to have the ability to Push messages to Web applications. It defines how web applications subscribe to Push service, how to respond to Push messages, and the authentication and encryption mechanism between Web applications, application servers and Push service. Since the Push API does not depend on the Web application and browser UI to survive, even when the Web application and browser are not opened by the user, the background process can receive Push messages and call the Notification API to notify the user


self.addEventListener('push', event => {
    event.waitUntil(
        // Process the event and display a notification.
        self.registration.showNotification("Hey!")); }); self.addEventListener('notificationclick', event => {
    // Do something with the event
    event.notification.close();
});

self.addEventListener('notificationclose', event => {
    // Do something with the event
});

Copy the code

The PWA has a long way to go

  • China pays more attention to iOS, and iOS is very unfriendly to PWA.

  • Domestic Android is really “Android”, not Chrome, secondly, manufacturers like their own blind overtime (JB) customized various systems, bringing compatibility problems

  • Push Notification is still in its infancy (there is no standard protocol yet) and the future is uncertain

  • Web application portals in China are mostly concentrated in various apps, such as wechat and QQ, which bring more restrictions

WebAssembly

Some pictures and concepts from the reference link: https://hacks.mozilla.org/2017/02/a-cartoon-intro-to-webassembly/

Brendan Acker: You said your boss is crazy about getting an app every 10 days? Eldest brother 10 days dry a language

Just because JS was born less “formal”, it introduced a lot of pothholes and performance limitations. It’s more like a building under construction that we web developers are constantly adding to that will one day become a skyscraper!

What is a WebAssembly

  • WebAssembly is a new specification developed by the W3C community of major browser vendors.

  • It is shortened to “.wasm”, a file name suffix, and is a new low-level secure binary syntax.

  • Can run close to native performance and provide a compilation target for languages such as C/C ++ so they can run on the Web. It is also designed to coexist with JavaScript, allowing the two to work together.

  • It can break the running speed bottleneck of front-end 3D game, VR/AR, machine vision, image processing and so on

Let’s look at a demo:http://webassembly.org.cn/demo/Tanks/

How WebAssembly works

Before we look at WebAssembly, let’s take a look at how the code works

In the code world, there are usually two ways to translate machine language: an interpreter and a compiler.

If done through an interpreter, translation is performed line by line as it is explained

The interpreter starts and executes faster. You don’t need to wait for the entire compilation process to complete before you can run your code. Start translating from the first line and you can continue.

When you run the same code more than once, however, the interpreter’s shortcomings become apparent. For example, if you execute a loop, the interpreter will have to translate again and again, which is inefficient.

A compiler compiles the entire source code into object code, which runs directly on a platform that supports object code without the need for a compiler.

It takes some time to compile the entire source code and then generate the object file for execution on the machine. Code with loops executes faster because it does not have to translate each loop repeatedly.

The first browsers were interpreters-only, because interpreters seemed to work better with JavaScript. It’s important for a Web developer to be able to execute code quickly and see the results. Later compilers were added to form a hybrid mode.

Add a monitor that monitors how the code is doing, how many times it has been run, how it is running, and so on.

What are the benefits of adding so many things

Initially, the monitor monitors all code passing through the interpreter.

If the same line of code is run several times, the snippet is marked as “warm”, and if it is run many times, it is marked as “hot”.

If a piece of code becomes “warm,” the browser sends it to the compiler for compilation and stores the compilation results. — (Baseline compiler)

Each line of the code snippet is compiled into a stub, which is assigned an index of line number + variable type. If the monitor monitors the execution of the same code and the same variable type, push the compiled version directly to the browser.

If a piece of code becomes “very hot,” the monitor sends it to the optimized compiler. Generate a faster and more efficient version of the code, and store it. — (optimizing the compiler)

The optimization compiler makes some assumptions. If the objects in each previous iteration of a loop have the same shape, the optimization compiler can assume that the objects in subsequent iterations have the same shape. This is never guaranteed with JavaScript. The first 99 objects hold their shape, and maybe the 100th object is missing a property, at which point the execution goes back to the interpreter or the baseline compiler, called de-tuning

function arraySum(arr) {
  var sum = 0;
  for (var i = 0; i < arr.length; i++) { sum += arr[i]; }}Copy the code

Sum and arr[I] are not guaranteed to be integers. Arr [I] may become a string, which is optimized. Reassign to the interpreter or baseline compiler

How does that translate?

There is not just one way we translate machine code, different machines have different machine code, just as we humans speak a variety of languages, machines also “speak” different languages.

One way you want to translate from any high-level language to one of many assembly languages (depending on the machine’s internal structure) is to create different translators for the various high-level language-to-assembly mappings.

This kind of translation is really inefficient. To solve this problem, most compilers add an extra layer in the middle. It translates high-level language to a lower level that is not down to the machine code level. This is intermediate representation (IR).

The front end of the compiler translates high-level language into IR, and the back end of the compiler translates IR into assembly code for the target machine.

The key to the

Where is WebAssembly? In fact, you can think of it as another “target assembly language.”

Each of the target assembly languages (x86, ARM) relies on a specific machine structure. When you want to execute your code on a user’s machine, you don’t know what the target machine structure looks like.

Unlike other assembly languages, WebAssembly does not depend on a physical machine. It can be understood abstractly as the machine language of conceptual machines, rather than the machine language of actual physical machines.

For this reason, WebAssembly directives are sometimes referred to as virtual directives. It maps more directly to machine code than JavaScript code, and it represents an idea of how code can be executed more efficiently on general-purpose hardware. So it doesn’t map directly to the machine code of a particular hardware.

Why not just use JS instead of WebAssembly

This is the distribution of JS performance usage

  • Parsing — the time it takes to turn source code into code that the interpreter can run;

  • Compiling + Optimizing — represents the time spent on the baseline compiler and optimizing compiler. Some optimization compiler work that does not run on the main thread is not included here.

  • Re-optimizing — Includes time to re-optimize, discard and return to the baseline compiler.

  • Execution — The time that code is executed

  • Garbage collection – Garbage collection, the time it takes to clean up memory

This is WebAssmbly versus JS

The advantage of WASM is that the binary files optimized by the compiler can be directly converted to machine code, eliminating the need for Javascript parsing and optimization, so it has advantages in loading and execution

Specific advantages

  • File access

WebAssembly has a higher compression rate than JavaScript, so file retrieval is faster. Even though compression algorithms can significantly reduce the package size of JavaScript, the compressed WebAssembly binary is still smaller.

This means that transferring files between server and client is faster, especially if the network is poor.

  • parsing

JavaScript source code is parsed into an AST (Abstract Syntax tree) when it arrives at the browser. Once parsed, the AST (abstract syntax tree) becomes intermediate code (called bytecode), which is provided to the JS engine for compilation.

WebAssembly does not require this transformation because it is itself intermediate code. All it has to do is decode and check to make sure the code has no errors.

  • To optimize the

The browser JIT will repeatedly “discard optimized code <-> re-optimize”. For example, if the variable type used in this loop is not the same as that used in the last loop, or if a new function is inserted in the prototype chain, the JIT will discard optimized code and re-optimize it.

In WebAssembly, types are determined, so the JIT does not need to make optimization assumptions based on the type of a variable. That is, WebAssembly has no re-optimization phase.

  • The garbage collection

The concept of memory in JS is very vague, because JS does not need to apply for memory, all memory is automatically allocated by JS, because it is not controllable, so garbage cleaning will bring performance overhead

WebAssembly does not require garbage collection, and memory operations are manually controlled (like C and C++). This does increase development costs for developers, but it also makes the code more efficient to execute.

How to implement a WebAssembly Demo

Refer to the link: http://webassembly.org.cn/getting-started/developers-guide/

int square (int x) {
  return x * x;
}
Copy the code
emcc math.c -s WASM=1 -o index.html
Copy the code

Complete the tank battle example from 0

4. You’re done

Thank you.

Spread the word

This article is published in Front of Mint Weekly. Welcome to Watch & Star.

Welcome to the discussion. Give it a thumbs up before we go. ◕ ‿ ◕. ~