[book intensive reading] “mobile web front end advanced development practice” intensive reading notes sharing


Write on the front

  • Book Introduction: “advanced development practice of mobile web front end” covers all the key technical links in the development of mobile web front end. From HTML5, CSS3, ecmascript5 and ecmascript6 versions of JavaScript, common layout schemes of mobile terminal, new era framework of MV * class, precompile technology, performance optimization, development and debugging, hybrid application, unit testing, engineering and other aspects, the web front-end technology stack of first-line Internet companies is comprehensively restored.
  • My brief comment: this book has a large capacity and comprehensively summarizes the excellent practice of various technical links related to the front-end technology stack. For those who are still at a low and intermediate level, it is recommended to read this book several times and check the missing points according to the key technical links introduced in the book.
  • !! Welfare: at the end of the article, there are pdf books, note mind map, package and download address with book code. Feel useful, remember to like or collect!
  • Links to the original articles of the series: https://github.com/yzsunlei/javascript-book-reading

The first chapter introduces the mobile web front end

  • Mobile web development is a subset of front-end development, specifically refers to the web front-end development work on mobile devices

1.1. Mobile web front end history

  • Web development can be divided into three phases: static technology phase, dynamic technology phase and post Web2.0 phase
  • HTML5 has the following characteristics: semantic; Local storage; Equipment compatibility; Connection characteristics; Multi-Media; Graphics Effect
  • HTML5 technology commonly used in mobile web development: view control; Media inquiry; Audio and video broadcasting;
  • 1. Advantages of mobile Web: cross platform, low development cost and easier iteration
  • 2. Disadvantages of mobile Web: limited function; Poor operation experience; Cannot be used offline; It’s hard to find;
  • 3. Advantages of native application: perfect function; Better experience; It can be used offline; High chance of discovery;
  • 4. Disadvantages of native application: high development cost; The iteration is uncontrollable; Content limitation;

1.2. Current situation and future of mobile web front end

  • There are still many problems to be solved in mobile Web: 1; 2. Network speed is still the bottleneck of performance; 3. High threshold caused by multi frame;
  • Knowledge system: basic computer knowledge; Static page making; programing language; Development tools; Mobile frontier technology; browser; Code quality; Engineering; Library / framework;
  • The inflection point comes from Google’s Web mailbox Gmail launched in 2005
  • The most fatal disadvantage of native app is that every update needs to be released, and users need to re install it

The second chapter is the construction of mobile web development environment

2.1. Visual studio code free cross platform editor

2.2. Use node.js

  • Node.js can realize almost all applications, but it needs to be used according to the business and project

2.4. Web proxy tool nproxy

  • There is Fiddler on windows and Charles on MacOS
  • Nproxy is a tool that can be used on multiple terminals

2.2.5. HTTP Server HTTP server

  • A simple zero configuration command line HTTP server is very suitable for daily testing, local development and other environments

Chapter 3: HTML5 features

3.1. New semantics

  • The arrival of new elements: let the machine recognize the semantic header, NAV and article in HTML structure; HTML5 also provides many semantic tags, such as address, mark, time and so on;
  • Enhanced application of form: 1. Extension of type attribute of input element, such as number, date, color, etc; 2. Input validates the form by attributes, which are implemented by required and pattern attributes; 3. Other useful attributes of input element, such as autofocus, form, placeholder, etc; 4. New elements and special attributes of HTML5: contenteditable; The new features provided by HTML5 enable developers to process various types of input, verification, auto focus and other functions at the HTML level;
  • Use audio and video: HTML5 provides audio and video tags to embed audio and video in web pages

3.2. Access your device

  • Positioning the current geographical location: HTML5 provides the ability to obtain the user’s location in the new function; Geolocation API is accessed through navigator.geolocation global object;
  • Practice: call the camera to take a picture: HTML5’s getusermedia API provides the ability to access users’ media devices. Based on this feature, developers can access video and audio devices without relying on any browser plug-in; The latest standard getusermedia API is navigator.mediadevices.getusermedia;
  • Actual combat drill: realize a shake on the mobile phone: through the sensor, you can sense the change of the direction and position of the mobile phone; It can develop many interesting functions, such as compass, car racing game by tilting mobile phone to control the direction, and even more popular augmented reality game;

3.3. Offline and storage

  • HTML5 introduces application caching, which means that web applications can be accessed when there is no network
  • At the same time, it also provides a set of local storage mechanism, which allows developers to store a small amount of data locally to improve the user experience
  • Practical exercise: build a simple offline application: HTML5 offline function includes offline resource cache, online status monitoring, local data storage, etc
  • How to update resources after offline service worker: HTML5 provides another set of API to help developers fully control offline data to support better offline experience; Service worker mainly provides four kinds of functions: background message passing, network proxy, offline cache and message push; Developers can also decide when to cache and update by communicating with the server;
  • Local storage and session storage: before HTML5, the common data storage scheme for web applications was generally implemented by cookie; The disadvantages of storing data in cookie are: limited size, consumption of performance;
  • Practical exercise: using indexeddb to realize memo Management: indexdb is a transactional database system, and also an object-oriented database system based on JavaScript; Indexeddb can store a large number of structured data and use index based efficient API retrieval;

3.4. Image effect

  • HTML5 introduces canvas and SVG tags to provide more rich graphics rendering functions for browsers
  • Webgl is used to render interactive 3D and 2D graphics in any compatible web browser
  • Using SVG to realize the five Olympic rings: to make the five Olympic rings linked, a simple and crude way is to “mend the knife”, and use the path label or line label to draw a new arc or line segment to create visual differences
  • The 3D space seen in canvas is not the real 3D space, but the simulated 3D space is projected to the image of 2D view by mathematical algorithm
  • In webgl, there are two ways to project objects from three-dimensional space to two-dimensional space: orthogonal projection and perspective projection. Orthogonal projection is to draw according to the same size regardless of the distance between the object and the viewpoint. In perspective projection, the closer the object is, the larger the distance is

3.5. Different communication

  • Postmessages: in the past, cross source or window communication was often realized by data interaction with the server, and polling or comet technology was needed to monitor messages; HTML5 provides a new mechanism, PostMessage, to achieve secure cross source communication;
  • XMLHttpRequest Level2。 Compared with the old version of the improvement: set the HTTP request timeout; Use the formdata object to manage the form data; For uploading files; Cross domain request; Get the binary data of the server; Obtain the progress information of data transmission;
  • Server sent event: the traditional method is that the client sends a polling request to the server, and once there is new data, it will be updated immediately. This method consumes performance and has poor timeliness; HTML5 provides server sent event, which has the following advantages: lightweight, relatively simple; Single transmission data; Based on HTTP protocol; It supports disconnection and reconnection by default; User defined sending data type; The server sent event receives the notification of the event sent by the server through the eventsource object;
  • Websocket: websocket is a new protocol of HTML5, which is based on TCP connection for full duplex communication; Websocket object provides a set of APIs for creating and managing websocket connections, and for sending and receiving data through the connections;
  • Webrtc: full name of Web real time communication, namely web real-time communication, which can provide real-time voice or video call function for browser and mobile web application; Webrtc includes the following major JavaScript APIs. Mediadevices provides a way to query and access media input devices; Rtcpeerconnection provides the method to establish the connection between points, and maintain and monitor the connection. The video stream and audio stream can be transmitted between the connected points; Rtcdata channel can be used to transmit arbitrary data between points; Webrtc has become the most important multimedia communication solution on the web. It can realize the transmission of audio, video and data based on browser without relying on browser plug-in, which provides rich and colorful real-time multimedia functions for web developers;

3.6. Other common features

  • History API and single page application: single page application means that web applications can switch between different pages without refreshing, and page access records will be saved by the browser, so as to support the forward, backward and refreshing operations of the browser; HTML5 adds pushstate and replacestate API to Xiangshan in history, which can be used together with the new popstate event on the window object to realize the single page application function;
  • Drop and drop introduction: before the drop and drop functions are provided, developers need to realize the drag and drop effect through the MouseDown, MouseMove, mouseup and other events of elements; The new drop and drop functions of HTML5 not only provide a standard event format, but also support the drag and drop of desktop files to the browser, which greatly simplifies the development complexity;
  • Using web workers to speed up application Computing: Javascript is a single thread, if an operation is very time-consuming, the page will be in the “suspended animation” state; Web workers endows JavaScript with the ability of multithreading, which can run time-consuming operations in web workers thread to prevent page from feigning death;
  • Using performance API to analyze website performance: to collect website performance in the early stage, you need to insert corresponding scripts into the page and listen to events in different periods of the page, such as domcontentloaded event. This method is highly invasive and can collect less information; HTML5 provides a web performance API that can obtain detailed performance indicators of page loading, which is exposed to developers through the window. Performance object; The window.performance.timing object contains the complete web page loading performance data;

Chapter 4 CSS3 must know practical skills

  • As an upgrade of CSS technology, CSS3 has been widely used on the mobile end, such as fillet, transparency, shadow, animation, responsive and other functions

4.1. Understanding CSS3

  • CSS, which means cascading style sheet in Chinese, is a style sheet language used to layout and beautify web pages
  • What is css3:1. Selectors: the new selectors can reduce the use of redundant class, ID or JavaScript; 2. Box model: provide box sizing property to change the calculation method of element width and height in the default CSS box model; 3. Personalized font: the introduction of @ font face rule allows developers to specify online fonts for web pages. One common use is Icon Font; 4. Adaptive layout: provides Calc function to dynamically calculate attribute values during rendering, which is commonly used in adaptive layout; 5. There are many other exciting new features, such as (rounded border, font shadow), which can only be achieved through pictures before; Responsive layout media queries, flexible layout flexbox and multi column layout; Comparable to the transition and animation effects of native applications;)
  • CSS3 status of mobile Web: if you want to know the support of a CSS3 attribute in a specific browser, you can use caniuse.com
  • Use moderniser to detect whether the browser supports CSS3: moderniser, a JavaScript library used to detect HTML5 and CSS3 features of the user’s browser; To realize the dynamic feature detection of browser, there are generally two ideas as follows: first, get the user agent with JavaScript, then judge the version of the browser according to the user agent, and then determine which attributes are supported in the current browser according to the version of the browser. The disadvantage is that it is not accurate; The idea adopted by moderniser is to use the specified attributes directly in JavaScript. If it is executed successfully, it means that it supports JavaScript; Another important function of moderniser is custom feature detection. When the browser is Internet Explorer 7, moderniser will add “IE7” style class name to HTML element, and call moderniser.ie7 in JavaScript to return true;)

4.2. Selector

  • Common selectors
  • Pseudo class and pseudo element: pseudo class is used to specify a specific state or condition of selector. Pseudo class does not exist in DOM, but it is visible to users; Dynamic pseudo class classifies elements with features other than name, attribute or content, and will not be displayed in document source or document tree; Pseudo element refers to the abstract content that does not exist in the document tree;
  • Priority and weight: the weight in CSS is divided into four levels: inline style; ID selector; Class, pseudo class, attribute selector; Elements, pseudo elements; Another special rule is “! “Important” can promote the corresponding rules to the highest weight; Reasonable planning of CSS selector weight is a good start to complete an easy maintenance project;

4.3. Responsive development

  • Width and height of common devices: the essence of responsive development is to adapt to a variety of screens; First of all, we have to master several basic concepts: physical pixel, device independent pixel and screen pixel ratio; The logical size of the user interface can be adjusted by setting the viewport property. The size of the page CSS is based on the viewport;
  • Flex elastic box layout: before flex appeared, layout was based on box model and depended on display, position and float style attributes; 1vw refers to 1 / 100 of the width of the current page’s viewport; After using flex layout, the styles of float, clear and vertical align of child elements are invalid;
  • Media query: the difference of resolution expands, which makes it necessary to present different interfaces to users according to the resolution of the screen; Using media query, different styles can be applied to different devices;
  • Developing responsive design with REM: REM refers to the font size relative to the root element
  • Multi column: CSS3 multi column layout is an extension of block level layout mode, which allows text to be multi column layout by simple definition; It should be emphasized that multi column layout is a layout for text arrangement, which is different from the general layout of left, middle and right columns;

4.4. Dynamic effect

  • Conversion: in March 2009, W3C released draft standards for 3D deformation animation and draft standards for 2D deformation animation, which allow developers to move, scale, rotate and tilt elements
  • Transition: CSS3 animation includes transition and animation, both of which can achieve the animation effect by changing the CSS attribute of the element; transition: property duration timing-function delay;
  • Animation: CSS3 animation is suitable for all block elements and inline elements. Complex animation effects can be achieved by defining key frames in animation; animation: name duration timing-function delay iteration-count direction;

4.5. Common features

  • Some common features in CSS3 include open font format, background, color, text effects, border and user interface
  • Open Font Format (woff): Web Open Font Format (woff) is a font format standard for web pages; Woff includes sfnt based fonts (such as postscript, TrueType and OpenType); The advantage is that it can reduce the file size effectively by using compression, and it does not include encryption and is not limited by copyright;
  • Background: background size, background origin and background clip are new attributes in CSS3
  • Color: commonly used to set font color, but also used in the background color of elements, linear gradient and radial gradient
  • Text effects: four commonly used: text shadow, text overflow, word wrap, word break
  • Border radius, border image, box shadow

4.6. Precompile

  • The main features of CSS language are: variable, operation, loop, function and scope
  • The commonly used pre compiled languages are less, sass, stylus and so on

Chapter 5 JavaScript key syntax and use skills

5.1. Understanding JavaScript

  • JavaScript is a script language supported by browser and an implementation of ECMAScript language. It is a dynamic script language based on prototype and multi paradigm, and supports object-oriented, imperative and declarative programming styles (such as functional programming)
  • JavaScript includes DOM (document object model) and BOM (browser object model)
  • Language basis: 1; 2. Data type; 3. Operators; 4. Conditions; 5. Circulation; 6. Function; 7. Abnormal
  • Functions and parameters: official explanation: functions are reusable code blocks that are event driven or executed when called; Function declaration: function type, variable type; Arguments is not an array

5.2. Events

  • Event overview: event is an implementation of asynchronous programming, is the communication between the various components of the program; The event is not a JavaScript object, but a mechanism to transfer information, so the event itself cannot carry any data content; Browser carries event data information through event object of JavaScript. When an event occurs, the browser stores the original data related to the triggered element and location into the event object, and then the program gets the response data through event monitoring; Several concepts to understand (event type, event target, event handler, event object, event propagation)
  • Event delegation: the early event model was implemented by Dom element attributes, that is, directly registering events for DOM elements in the form of object attributes, which is called DOM event model; The dom2 event model mainly implements two technologies: supporting the registration of multiple events of the same type for the same DOM element; The event is divided into capture phase and bubble phase; The dom2 event model adds event listening to the element object through the addeventlistener method. When listening to events for many times, they will not cover each other as before, and each listening is effective; The way of handing an event to a parent element or ancestor element is called event delegation; There are two main advantages of event delegation: improving performance: each function takes up space, and only one event handler is added, which takes up less memory space; Dynamic monitoring: use delegation to monitor future elements;
  • Events designed for mobile terminals mainly include three types: touch events, gesture events and sensor events

5.3. Scope, closure and this

  • In JavaScript, functions are “first class objects”, which allows JavaScript functions to be stored in variables or other structures, as return values of other functions, or passed as parameters to other functions
  • Closures can be used to store intermediate calculation results, similar to the implementation of the cache of calculation results
  • Another use scenario of closures is to encapsulate internal variables, that is, to encapsulate singleton patterns of private members with anonymous functions
  • The JavaScript this keyword represents the internal object generated by the function runtime. Unlike the variable search process, the value of this is obtained from the execution context instead of searching in the scope chain
  • There are several ways to call a function: as a function call, as an object method call, as a constructor call and use call and apply call

5.4. Object oriented

  • JavaScript is an object-based language. But the writing is different from the traditional object-oriented programming language
  • Prototype and prototype chain: in JavaScript, inheritance is realized by prototype chain. The concept of object prototype often puzzles many beginners of JavaScript. In fact, prototype based inheritance model is more powerful than traditional class inheritance. JavaScript can simulate class inheritance through prototype inheritance, but it is much more difficult for a class inheritance model to simulate prototype inheritance; There are four ways to create objects and prototype chains: 1. Using common grammar to create objects; 2; 2. Using constructors to create objects; 3. Use object. Create to create objects; four__proto__prototypeandconstructor
  • Mixin mode: Javascript implements inheritance through prototype chain, but the inheritance is based on a single prototype chain, which means that only a unique prototype can be inherited; Mixin pattern is a solution for developers to introduce multiple inheritance. Mixin is a combination of multiple inheritance;
  • Ecmascript6’s class and extensions: for developers of traditional object-oriented languages, prototype chain is easy to cause confusion. As syntax sugar, class and extensions solve developers’ confusion about JavaScript inheritance; The inheritance implemented by Extends is more intuitive than the prototype chain. The subclass needs to call the super method to execute the parent class constructor in the constructor constructor.

5.5. Asynchronous programming

  • Callback function in Ajax: determine the value of readyState property by listening to the readystatechange event
  • Promise mode: through the then method of promise object, the data of asynchronous successful callback is obtained. Through the catch method, the error information of asynchronous call is captured. At the same time, the then method supports multiple chain calls; Through promise. All and promise. Race methods, it is easy to control the parallel execution of multiple promises
  • Generator: iterator is a new syntax of ecmascript6. The iterator object can use for… Of loop to traverse all its subitems; Due to the characteristics of the generator, the next method is called to execute an interval of code each time, that is, the generator provides a segmented execution mechanism

5.6. Modularization

  • The principle of modularization is “high cohesion, low coupling”
  • “High cohesion” reduces cross references of functions in different files as much as possible, “low coupling” means that modules should be independent of each other
  • The purpose of modularization is to reduce the complexity of program and simplify the operation of program design, debugging and maintenance
  • Why modularization is needed: in the early development of JavaScript, AJAX was not popular, and JavaScript was just a “toy language”, which was used to check forms on Web pages and achieve simple animation effects; Huge and complex applications need a team to work together, schedule management, unit testing, etc. developers have to use software engineering methods to manage the business logic of web pages; The exploration of some writing methods of modularization (1. Original writing: putting a group of functions to realize functions in the same file; 2. Add a namespace: use the single global variable mode; 3. Functions executed immediately: actually anonymous functions)
  • AMD and CMD specifications: common JS, AMD and CMD specifications are the most popular modular specifications; Node.js is the implementation representative of common.js specification, and requirejs is the implementation representative of AMD specification. The representative of the implementation of CMD specification is sea. JS;
  • Ecmascript6 standard module support: ecmascript6 did not support native modularization until now. It not only has the advantages of commonjs specification and AMD specification, but also has more friendly implementation, simpler syntax than commonjs, better support for compile time loading or static loading, and better loop dependency handling; The function of ecmascript6 module is mainly composed of two commands: export and import / export command are used to specify the external interface of the module, and Import command is used to input the functions provided by other modules; The export command specifies the external interface and must establish a one-to-one correspondence with the internal variables of the module;

5.7.ecmascript6 other common functions

  • Extension of basic data type: a minimal constant epsilon is added to the number object
  • Use deconstruction assignment to simplify code: any data structure that implements the iterator interface can be deconstructed in array mode
  • Using Babel plug-ins to use new features ahead of time

Chapter 6: HTML5 mobile development

  • Through a number of actual development scenarios, such as geolocation, online chat, shooting, player, animation, 3D and so on
  • Display the walking track on the map: use the gaude map; Get the current geographic location through navigator.geography.getcurrentposition of HTML5; The method of navigator.geography.watchposition is used to monitor the change of geographic information to display the walking track

6.2. Copy original album

  • Through the touchstart, touchmove and touchend events, the left and right sliding operations are realized

6.3. Using socket.io to make small chat room

6.4. Practice of photo upload on mobile terminal

  • Functions include photo upload, real-time progress display and picture preview

6.5. Using microdata to optimize SEO

  • Microdata technology is introduced into HTML5
  • This technology aims to make the network more intelligent, such as providing information acquisition, information filtering, web automatic services and so on

6.6. Make a video player with subtitles

  • The example player contains three common function buttons: play, fast forward and mute
  • Webvtt format file, full name of web video text tracks, Chinese means web video text track

6.7. Use pixi.js to make the game of “catch the new year”

  • Pixi.js is an efficient and open source 2d rendering engine, which mainly supports webgl API of hardware GPU rendering
  • Pixi.js can be used to develop “rich vision” applications such as interactive graphics, animation and games

6.8. Making scraping card with canvas

  • Canvas is a new element of HTML5, which is used for drawing graphics, such as drawing path, box, circle, character and adding image

6.9. Actual combat drill: realize 3D panoramic effect

  • Transform: applies a 2D or 3D transformation to an element
  • This property allows elements to be rotated, scaled, moved, or tilted

Chapter 7 mobile web page style layout practice

  • It is necessary for a qualified front-end development engineer to master the style and layout of mobile web pages effectively

7.1. Practical application of static layout

  • The feature of static layout is that the size of the layout will not change with the size of the browser window adjusted by the user
  • The traditional PC side generally chooses 960 pixels. This width can be adapted by all modern browsers, and can be divided by the mainstream screen width. The mobile terminal generally selects 320 pixels
  • The adaptation of static layout on mobile terminal: 1; 2. Media inquiry;
  • Media query will greatly increase the amount of code. Two points should be paid attention to: first, put the attributes that do not need to change according to the screen outside the media query to reduce code redundancy; Second, set the media query breakpoints

7.2. Horizontal center and vertical center actual combat

  • Horizontal center: set the style text align to center for the element in the row; For block level elements, set the margin value to auto; Block level elements (fixed size) can also be horizontally centered by absolute positioning + negative outer margin;
  • Adaptive block level elements are in the middle: transform is used to achieve the effect;
  • In line element vertical center: set the element height equal to the line height for single line text; Multi line unfixed height can be achieved by setting padding; Fixed height multiline text can be used display:table-cell Cooperate with vertical- align:middle realization;
  • Vertical center of block level elements: fixed height and width can be achieved by absolute positioning and negative margin; The unfixed width and height need to be processed by translate deformation function;
  • The solution based on the unit of view: using the length unit 1vw to represent 1% of the width of view;
  • Flexbox based solution: the best solution recommended at present;

7.3. Grid system realizes responsive list

  • Grid layout is a kind of responsive layout handed down from the era of desktop browser
  • The grid system is composed of container, row and column. The row is contained in the container, and only the column can be used as the direct child element of the row

7.4. Flex multi column layout

7.5. Actual combat drill: real combat 24

7.6. Actual combat drill: sidebar sliding in and out effect

  • In mobile development, due to the limited screen space, some menus or function floating windows are often hidden on one side of the screen. When you click the expand button, the content will be presented with the effect of sliding out

7.7. Actual combat drill: simulate the original page switching effect

  • In web applications, page skipping will lead to resource reloading, which may lead to a long time of white screen waiting. Therefore, in order to achieve the page switching effect of imitating native applications, it needs to be presented in the form of a single page web application

7.8. Improve the performance of Web Animation

  • Using CSS3 Animation: when rendering DOM, the actual work of the browser is performed from top to bottom; Set the transform attribute. In some advanced browsers, this attribute will trigger a new layer, or even start the hardware acceleration of the device. In this way, the main point of performance consumption is only focused on the combination of layers; Style opacity is also a CSS property that triggers GPU acceleration;
  • Use high-performance JavaScript Animation: 1. Remove layout bumps (separate acquisition and setting, a series of browser operations at the same time, can be optimized to a single operation; 2; In some loop calls, when setTimeout or setinterval is used for animation call, unreasonable time setting will also cause page jam. In this case, request animation frame is recommended; 2. Use the throttling function (Backjump is to call the action within n milliseconds, and the action will be executed. If the action is called again within n milliseconds, the time will be recalculated; Throttling is to first set an execution cycle, when the call time is greater than or equal to the execution cycle, it will execute and enter the next cycle; If you want to optimize JavaScript animation more conveniently, you can choose to use excellent third-party animation library, such as velocity. JS)

7.9. Actual training: course classification list actual training

7.10. Summary of this chapter

  • The layout of mobile web page is different from the traditional PC layout. In the design and implementation, we need to focus on the restoration of devices with different terminal sizes. In the technology selection, we are more and more inclined to use the new features of CSS3

Chapter 8 front end engineering practice

  • Software engineering is a subject that studies how to develop and maintain software systematically, normatively and quantitatively. It includes two aspects: software development technology and software project management
  • The goal of software engineering is to develop software products with applicability, effectiveness, modifiability, reliability, comprehensibility, maintainability, reusability, portability, traceability, interoperability and user requirements under the premise of given cost and schedule

8.1. Front end Engineering

  • Without an engineering system, efficiency, quality, cooperation and maintenance are impossible
  • The necessity of front-end engineering: 1. Standardize code; 2. Preprocess JavaScript; 3. Preprocess CSS; 4. Auto compile; 5. Reduce file size; 6. Code sharing, auto deployment, workflow management, etc
  • The development history of front-end engineering: 1. Stone Age (only need to realize the simplest content presentation and form submission). Use static HTML code to provide basic browsing content; 2. Bronze Age (the realization of web component development and asynchronous loading); 3. Agricultural era (module loading specification emerges as the times require, and there are many frameworks for dynamically loading JavaScript code based on the specification); 4. In the industrial era (to reduce the difficulty of development, front-end MVC, MVP, MVVM frameworks have sprung up, such as backbone, react, etc.); There are also many automation oriented building tools, such as grunt, gulp, webpack, etc.)

8.2. Introduction to engineering grunt

  • Grunt is a powerful task manager based on JavaScript, which allows the verification of JavaScript syntax, CSS compression, sass compilation and other tasks on the terminal. It can realize automatic construction, testing and so on
  • The main function of gruntfile file is to configure or define task; Load the grunt plug-in;

8.3. Building applications with gulp

  • Using grunt to build a project involves disk operation, so the efficiency is low. Therefore, flow based gulp emerges as the times require
  • The gulp.src method returns the stream object, and the content can be passed to the plug-in through the pipe method
  • Babel can compile JavaScript files, even react JSX files, into standard JavaScript files
  • Indexeddb manages the structure of the database by version, so the code stored in the database or object must be modified in the upgraded event

8.4. Using webpack to build applications

  • Webpack is a module loader and packaging tool, which can process all kinds of resources, such as scripts (JavaScript, typescript, JSX), styles (CSS, less, SASS), pictures (PNG, JPG, GIF) as modules
  • The function of loader is to convert the format of the source file in the project. It exists in the form of function, receives the source file as the input parameter, and outputs the converted resource file
  • When webpack refers to a module, there are three ways to specify the module path: relative path, absolute path and module path
  • By default, all resources of a single page application will be compiled into a unified file
  • Require.ensure will only load the module, not execute the module, so be sure to use require to execute the requested module in the callback function

Chapter 9: the common development methods of mobile web

  • Mobile web developers have gradually moved from the early DOM based development mode to MVC / MVVM class library framework. The representative frameworks are react and vue.js, and the original multi page development mode has changed into single page application mode

9.1. Development mode based on DOM

  • Zepto is a small JavaScript class library, and most of its APIs are consistent with jQuery
  • Solve the defect of native click event: double click scaling, 300 ms delay
  • Why do we abandon the zepto: touch module and add a new tap event to remove the click delay, but a new problem called “point through” arises; Zepto is also far less efficient than jQuery in basic DOM operations;
  • The main design ideas of current mainstream JavaScript framework are: 1. MVC and MVVM; 2. Front end routing; 3. Observer mode; 4. Modularization and componentization; 5. Data binding and state management; 6. Virtual dom

9.4. Create a single page application Spa

  • The idea of single page application is that all the code (HTML, JavaScript, CSS) is obtained in one page loading, or some resources are dynamically loaded when the page needs to be loaded
  • Through the hash value of the path or the technology provided by the history API of HTML5, the page Jump switch is realized in a single page, but the page is not reloaded
  • What are the advantages of single page applications: single page applications mainly rely on two technologies: one is the ability of JavaScript framework to provide rendering and page switching, the other is the ability of Ajax to provide front-end page and server-side data interaction
  • Practical drill: realize a single page Routing: there are two technical modes of Web Routing: Based on hash and history API; Refer to the source code of react router or Axios (vue2.0 recommended route);
  • Practice: using react to develop a simple single page application
  • State management of single page application

Chapter 10 mixed development practice

  • The concept of hybrid development combines the characteristics of native and web development, which is usually defined as developing a hybrid application using web technology in native container

10.1. Why hybrid development is needed

  • Mixed development types: 1. WebView mode (represented by phonegap and Cordova, which are mainly implemented in WebView through HTML, CSS and JavaScript); 2. JavaScript core mode (a new development mode, which calls native code to render native controls through JavaScript); 3. Wechat applet (independently designed a set of syntax corresponding to traditional HTML, CSS and JavaScript). Learn the react native class framework to render native components directly to improve performance, and get a smooth experience by using offline cache; 4. Flutter (radical implementation of the entire UI layer, which can be directly controlled by dart language). I hoped dart could replace JavaScript in browsers.)
  • Advantages of hybrid development: cross platform, rapid release and function improvement
  • Choose the appropriate hybrid development scheme: integrate three points (development efficiency, user experience, project complexity); Selection analysis (if there is a ready-made application and has a certain native development ability, you only need to embed the web page into the app to realize some dynamic display. You can choose to implement a set of WebView extension scheme to expose the native capabilities to WebView; The embedded H5 page is more complex or needs to build a complete app, and the developers are more specialized in Web technology, which is suitable for solutions such as phonegap or Cordova; Solve the differences of WebView models in Android system; Technologies such as react native or weex can not only realize complete application, but also embed app as a part of it. Close to the experience of native application, with platform compatibility problems and performance problems in complex scenarios)

10.2. Introduction to Cordova development

  • JavaScript and native call each other: the essence of hybrid development is the mutual call of JavaScript code and native code; 1. Native calls web (Java implementation in Android: WebView. Loadurl (“javascript: (function() {alert (‘call from native ‘)}”))); Swift implementation in IOS: WebView string byevaluating JavaScript from string (from: “alert (‘call from native ‘)); 2. Web call native (native call web is the dynamic execution of JavaScript script, while web call native is the process of getting JavaScript data and then executing or mapping to native code; Webview.addjavascriptinterface is the most popular method in Android. This method can map objects in Java to JavaScript, call functions under JavaScript objects, and trigger functions under native objects;
  • Introduction and installation of Cordova: Cordova is a cross platform solution based on WebView, and its core component is plug-in; Almost all the code needs to be executed after listening to the deviceready event, which means that the Cordova capability is injected after the WebView is created;

10.3.React Native

  • The biggest advantage is that it uses JavaScript as a bridge to call native methods and components, taking into account both performance and development efficiency
  • The package is jsbundle, which needs to be enabled through native container
  • The style and layout of react native is a CSS subset scheme based on flexbox
  • API is its internal exposed method. Through JavaScript object call, it can be used to obtain some native capabilities, similar to the functions provided by plug-ins in Cordova
  • Appregistry. The whole JavaScript needs to call this API to register in the native application. The native application runs the program through the corresponding appregistry. Runapplication

Chapter 11 front end development and debugging

  • Browser debugging, agent tools, multi terminal synchronization tools, simulator debugging, multi platform debugging, cloud real machine debugging and react debugging

11.1. Browser debugging

  • Chrome development tools
  • Safari developer tools

11.2. Agency tools

  • Through the proxy tool, you can capture packets and view the details of network requests
  • You can proxy online files to local files, and you can debug online problems without having to go online repeatedly
  • Two common proxy tools: Charles under Mac OS (by setting itself as the network access proxy server of the system, all network access requests are completed through Charles, so as to achieve the interception and analysis of network packets); Fiddler under windows can set up an agent between the local computer and the server. Through this agent, all requests and responses can be intercepted, modified and analyzed. You can also proxy static files on the website to local files to simplify the debugging process.)

11.3. Multi terminal synchronization tool

  • Two common multi terminal synchronization tools browsersync and emmetlivestyle
  • Browsersync enables the browser to respond to file changes in real time and quickly and refresh the page automatically. The files include HTML, JavaScript, CSS, sass, less, etc
  • Browsersync can be debugged on PC, tablet, mobile phone and other devices at the same time. All devices will display the modified effect at the same time
  • Two way auto refresh style tool emmetlivestyle

11.4. Simulator debugging

  • The simulator is a virtual device running on the local computer, which effectively alleviates the problem that developers cannot obtain a large number of physical devices
  • Compare the commonly used Android simulator software, recommend genymotion
  • IOS simulator needs Xcode tool under Mac OS system
  • Online Android simulator manymo

11.5. Multi platform debugging

  • The purpose is to test and debug multiple devices, mainly to solve the problem of compatibility and provide the efficiency of testing and debugging
  • Ghostlab is a Mac application for testing the synchronization of sites and web apps on multiple devices
  • Weinre, a debugging tool for mobile web development
  • Vorlon.js is an open source tool for JavaScript remote debugging and testing provided by Microsoft. It helps developers load, check, test and debug JavaScript code running on any device using web browser

11.6. Cloud real machine debugging

  • Browserstack is a multi system cross browser compatibility online testing tool, which supports cloud online testing of more than 1100 real machine and desktop browsers
  • STF is a comfortable web application that can remotely debug and manage smartphones, smart watches and other gadgets in the browser
  • Multi browser compatibility test platform f2etest

11.7.react debugging

  • React developer tools is a system tool provided by Facebook for developers to debug and use react rendering
  • Redux devtools is a Redux development and testing tool, which can record, play back and edit the status of Redux applications in real time

Chapter 13 front end performance optimization

13.1. Common website performance optimization indicators

  • 1. Resource request and loading phase of web page
  • 2. Web page rendering
  • 3. The execution speed of JavaScript script

13.2. Still effective Yahoo performance optimization rules

  • 1. Reduce HTTP requests
  • 2. Compress CSS and JavaScript code
  • 3. Remove the repeatedly referenced scripts
  • 4. Cacheable Ajax
  • 5. Delay loading unnecessary scripts
  • 6. Preloading
  • 7. Reduce the number of DOM elements
  • 8. Reduce DOM access times
  • 9. Avoid using iframe
  • 10. Optimize the image
  • 11. Optimize CSS sprites
  • 12. Don’t scale images in HTML
  • 13. Reduce cookie size

13.3. Actual use of performance optimization tools

  • 1. Yslow: a website performance analysis tool based on 23 testable performance rules in Yahoo rules
  • 2. Pagespeed: a performance optimization analysis tool provided by Google
  • 3. Webpagetest: the online version of the subproject of Google open source project “make the web fast”

13.4.http header caching

  • 1. Client caching process
  • 2. Cache protocol content: attributes related to cache in HTTP header (1. Expires: specify the time when the cache will expire; 2. Cache control: more detailed than expires policy, higher priority than expires; 3. Last modified / if modified since: Specifies the last modification time of the response resource; 4. Etag / if none match: a unique identifier to distinguish resource content, which needs to be used with cache control.)
  • 3. Practice: http cache

13.5. Resources loaded on demand

  • 1. On demand loading based on requirejs: the module is loaded asynchronously, so the module loading will not affect the subsequent code running; Amd loads the module through the require function and accepts two parameters module and callback;
  • 2. On demand loading based on webpack: Although the commonjs specification itself adopts synchronous loading module, it also proposes modules / async / a specification and defines a set of require.ensure to handle asynchronous loading
  • 3. Lazy loading of pictures: the principle of lazy loading is to load pictures when they enter the visual area by monitoring page scrolling events; In the real business scenario, we also need to consider the user’s pull-down speed, the fixity of page height, and the use of third-party plug-in libraries such as iscroll;

13.6. Optimization Practice of different network types

  • 1. Get network type: developers can get network types through navigator.connection.type, including unknown, Ethernet, WiFi, 2G, 3G, 4G, none
  • 2. Weak net image optimization: only integrate small icons into sprite image, and control the volume of each sprite image. If it exceeds the upper limit, integrate the second sprite image
  • 3. Weak network cache optimization: developers can choose to cache request data in memory

13.7. Practice: nginx configures combo to merge HTTP requests

  • 1. Install nginx and file merge module
  • 2. Configure nginx and combo

13.8. Summary of this chapter

  • The golden rule of Web optimization points out that only 10% – 20% of the time to visit a web page is spent on downloading the HTML file responded by the server, and 80% – 90% of the time is spent on downloading and executing the front-end resources, such as CSS, JavaScript, images, etc

Chapter 14 project practice: building live broadcast platform

  • Crosswalk is used in the project to provide a unified WebView to solve the compatibility problem of webrtc
  • The process of live broadcasting is composed of collection, streaming, streaming, decoding and playing
  • Because webrtc needs the support of HTTPS, in this case, self signed certificate is used to implement HTTPS
  • HLS is an online video playback solution based on HTTP protocol proposed by apple, which is composed of a play list file (format m3u8) and a video clip (format TS)
  • When node.js is deployed in an actual project, in order to improve the scalability of the system, PM2 can be used to start and start the cluster mode
  • Using ffmpeg component to transcode video
  • The new technologies involved in this project include webrtc, websocket, react, ffmpeg, etc

Live broadcast process

  • Capture: the initiator calls the local camera to capture the video stream through the getusermedia method of the Navigator object
  • Push streaming: the initiator uploads the video stream to the server through websocket
  • Encoding: the server uses ffmpeg video frame to encode the video into TS format for storage
  • Pull stream: watch the encoded audio and video stream pulled from the server through HLS
  • Audio and video stream decoded at the viewing end
  • The viewing end plays the decoded audio and video stream

HLS technology is used to realize live video

  • Using webrtc interface to obtain audio and video information
  • Use mediarecorder to record video clips regularly and upload them to the server

–The server saves the video clip and generates m3u8 format file

  • Other clients participating in the live broadcast directly use m3u8 to play the live video

Write it at the back

  • Pdf book, note mind map, book code package download address: https://pan.baidu.com/s/1pi0CgI3LFnIdi2DPawKU9w (extraction code: 2942)
  • Purchase address of paper book Jingdong: fill in the following (it is recommended to use paper book to learn)
  • In order to facilitate the mobile phone to see, I will post these notes to the official account “three pie four” later, I can scan code to pay attention to it, welcome to pay attention.
    [book intensive reading]