navigation

[Deep 01] Execution context [Deep 02] Prototype chain [Deep 03] Inheritance [Deep 04] Event loop [Deep 05] Curri Bias function [Deep 06] Function memory [Deep 07] Implicit conversions and operators [Deep 07] Browser caching mechanism (HTTP caching mechanism) [Deep 08] Front-end security [Deep 09] Deep copy [Deep 10] Debounce Throttle [Deep 10] Front-end routing [Deep 12] Front-end modularization [Deep 13] Observer mode Publish subscribe mode Bidirectional data binding [Deep 14] Canvas [Deep 15] webSocket Webpack HTTP and HTTPS CSS- Interview Handwriting Promise

[react] Hooks

[Deployment 01] Nginx [Deployment 02] Docker deployVue project [Deployment 03] gitlab-CI

[source code – Webpack01 – precompiler] AST abstract syntax tree [source code – Webpack02 – Precompiler] Tapable [source code – Webpack03] hand written webpack-compiler simple compilation process [source code] Redux React-redux01 [source] Axios [source] vuex [source -vue01] data Reactive and initial render

Front knowledge

Omit the end of each line in js; When semicolon, need to pay attention to the problem

  • () the statement before the parenthesis, which must be preceded by a semicolon or terminated by a semicolon
  • [] The statement before the brackets, which must be preceded by a semicolon or terminated by a semicolon
Omit the end of each line in js; - () the statement that begins with parentheses must be preceded by a semicolon or must end with a semicolon - [] the statement that begins with parentheses, must be preceded by a semicolon or must end with a semicolon example: (1) () the statement before the parenthesis, which is preceded by '; Var a = 1 (function() {// 错 误 : Uncaught TypeError: 1 is not a function console.log(a)})() (function () {< -- -- -- -- -- -- -- -- -- / / add a semicolon before () / / or in the var a = 1; Console. log(a)})() (2) [] = []; Var a = 1 [1,2,3]. ForEach (item => console.log(item)) // Uncaught TypeError: Cannot read property 'forEach' of undefined; [1, 2, 3]. The forEach (item = > console. The log (item)) < -- -- -- -- -- -- -- -- --Copy the code

scope

  • Scope: The scope within which a variable exists
  • Scopes are classified into global scope, function scope, and eval
<script> var a = 1 var c = 2 function x() {var b = 100 c = 20 } x() console.log(a) // 1 console.log(c) // 20; (function() {// Note that semicolons are required because ()[] starts at the end of the preceding statement, or ()[] starts with; Console.log (c) // 20})() console.log(b) </script>Copy the code

The process by which a browser parses a JS file

The browser loads javascript scripts, mainly through the script tag

  • (1) The browser begins to parse the HTML file while downloading itThat is: start parsing the HTML before it has been downloaded
  • (2) In the process of parsing, the script tag is provisionally parsed and the rendering control of the page is handed over to the javascript engine
  • (3) If the script tag references itExternal scripts,Download the script and execute it; ifThere is noitDirect executionThe code inside the script tag
  • (4) the javascript enginecompletedAnd return controlRendering engineTo restoreParsing HTML pages
Summary of browser parsing JS file process: 2. The script tag blocks HTML parsing, and if it takes a long time, it will cause browser suspended animation. 3. Problems that cause complex thread races and control contestsCopy the code

Js synchronous loading, JS asynchronous loading

  • Synchronous loading: blocks the page
  • Asynchronous loading: does not block the page

The script tag is loaded asynchronously as async defer

Defer: Is it deferred

  • (1) The script tag is placed at the bottom of the body

    • It’s not strictly asynchronous loading, but it’s a common way to improve page performance by changing the way you load js
  • (2) the defer attribute

    • Load asynchronously, do not block the page, and execute the JS file after DOM parsing is complete
    • Execute in sequence without affecting dependencies
  • (3) the async attributes

    • Asynchronous loading does not block the page, but async executes as soon as the asynchronous loading is complete. If the HTML has not been loaded yet, the page will be blocked
    • Note: Load asynchronously, loading does not block the page, execution does
    • The order of execution of each JS file is not guaranteed
  • Defer (1) load: It loads asynchronously and does not block the page; (2) Execution: The execution can be performed after DOM rendering, which can ensure the execution order of each JS
  • Async (1) loading: is asynchronous loading, loading does not block the page; (2) Execution: It is executed immediately after loading, and the execution order of each JS cannot be guaranteed
  • Defer, async, put at the bottom of the body, which method is better?

    • The safest thing to do is to<script>Written in the book<body>At the bottom, no compatibility issues, no white screen issues, no execution order issues

The tree command – generates the directory structure

tree [<Drive>:][<Path>] [/f] [/a]

Tree [<Drive>:][<Path>] [/f] [/a] /f: displays the names of the files in each directory /a: uses text characters instead of graphic characters to connect examples: C: │ index. The HTML │ ├ ─ a │ └ ─ b │ CCC. Js │ └ ─ requirejs a. s b.j s SAN Antonio sCopy the code

Immediately call function expression IIFE

IIFE Immediately- Invoked Function Expression (Function (){… }) (), (the function () {… } ())

  • Requirement: The function is called immediately after it is defined
  • Problem: If the function is called directly after parentheses, an error will be reported
    • Error: function () {} ();
  • 错 误 : The function keyword should not end with parentheses. 错 误 : The function keyword should not end with parentheses. 错 误 : The function keyword should end with parentheses
  • How to solve it: IIFE uses immediate call function expressions to solve it
    • Make it an expression, not a statement
    • Statements cannot end in parentheses, but expressions can
  • Knowledge points to master:
    • (1) How to pass parameters in IIFE
    • (2) When multiple IIFE's are used, the semicolon cannot be omitted
    • (3) IIFE does not pollute global variables because you do not have to name functions
    • (4) IIFE can form a single scope domain name, which can encapsulate some variables that cannot be read externally
    • (5) IIFE
Function expressions called immediately by IIFE need to be understood: (3) IIFE does not pollute global variables because there is no need to name functions. (4) IIFE can form a separate function name. Const obj = {name: 'woow_wu7'}; {name: 'woow_wu7'}; (function(params) {// params parameter console.log(obj) // obj console.log(params)})(obj); // obj is the argument // (1) // Note: the semicolon at the end is required because there are two IIFE calls in a row. 'woow_wu7} / / (2) / / IIFE two writing: / / 1. (the function () {... })() // 2. (function(){... }());}();}();}();}();} Function (params2){console.log(obj) console.log(params2)}(obj))Copy the code

Front end modularization

Concept of modules

  • To put the various parts of a complex program in accordance with certainRules (specifications)Encapsulated differentlyBlocks (different files)And put them together
  • The variables and methods inside the block are private, exposing only interfaces through which to communicate with the outside world

Non-modular problems

  • Contamination of global variables
  • Each js file internal variables modify each other, that is, there is only global scope, no function scope
  • If each module has a dependency relationship, the dependency relationship is vague, it is difficult to distinguish who depends on whom, and the dependency must be preceded
  • Difficult to maintain
<! DOCTYPE html> <html lang="en"> <head> <script> var me = 'changeMe'; // changeMe </script> <script SRC ="./home. Js "></script> <! -- var home = 'chongqing' --> <script src="./me.js"></script> <! -- var me = 'woow_wu7' --> <script src="./map.js"></script> <! -- var map = 'baidu' --> </head> <body> <script> console.log(window.me, 'global variable modified window.me') // 'woow_wu7' indicates that global variable console.log(map, // baidu var map = 'Amap' console.log(map, 'other module MAO was modified ') // Amap indicates that the module variable was modified, </script> </body> </ HTML >Copy the code

Benefits of modularity

You can memorize it. There’s an idea

  • Better separation: Instead of putting multiple scripts in one HTML, just introduce one overall script
  • Avoid name conflicts: variables within a module do not affect variables outside the module, that is, each module can have variables of the same command
  • Better handling of dependencies: Each module only has to worry about the dependencies of its own module, not the dependencies of other modules. If you introduce many scripts into an HTML, it becomes difficult to distinguish the dependencies of each script
  • Better maintenance

Problems that modularity needs to solve

  • Secure installation of the module, i.e. no contamination of any code outside the module
  • Uniquely identifies each module
  • Elegant exposure API, cannot add any global variables
  • You can refer to other dependencies

Comparison of different modular schemes

IIFE, CommonJS standard, AMD, CMD, modular scheme of ES6 CommonJS — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — node. Js use standard AMD: Asynchronous Module Definition —– Asynchronous Module Definition CMD: Common Module Definition ———– Universal Module Definition

  • Commonjs used in server, synchronous loading — — — — — — — — — — — — — — — — — — — — — — — — — — — — — – node. Js use standard
  • AMD and CMD are mainly used for browser side, asynchronous loading
  • Module solution for ES6: browser and server, generic solution, static
  • AMD pre-loaded dependencies, which must be written at the beginning, are pre-loaded (pre-loaded, pre-executed) ——– RequireJS
  • CMD dependencies are nearby, and only load dependencies when needed (dependencies are nearby, delayed execution) ————- seajs
  • ES6 modules are static, so the dependencies, inputs, and outputs of the module can be determined (at compile time); AMD and CMD can only be determined at run time

  • 2021/3/23 supplement
    • ES6 modular solution => Dynamic update
    • CommonJS => Module input is (value cache), there is no dynamic update
    • In the ES6 module
      • export { a, b }; The curly brace after export is not an object, but an interface with variables a and b in it
    • In the CommonJS
      • module.export = {a: 1}; What you export is an object
    Es6 module ------- export var foo = 'bar'; setTimeout(() => foo = 'baz', 500); The above code outputs the variable foo with the value bar, which becomes baz after 500 millisecondsCopy the code

The development of modularity

(1) Primitive stage – Only function scope

Var a1 = 'a1' function a1() {} function a2() {Copy the code

(2) Object encapsulation

Var a1 = {a2: function() {} a3: function() {}} Reduced the number of variables in the global scope: - there are only two in a3, A1 -------- while the full function: ---------- 3 disadvantages: 1. 2. External modifiers can modify attributes of A1, that is, all attributes are exposed and can be modified externallyCopy the code

(3) Modularity with IIFE(immediate call function expressions)

IIFE Immediately-invoked Function Expressions

  • The modular IIFE implementation solves the following problems:
    • You must not modify variables inside a module anywhere else
      • The inability to modify variables within a module elsewhere means that each module has its own (separate scope) and is not externally accessible
      • Functions have (function scope), and the variables inside the function cannot be accessed from outside the function
    • Variables within a module must not contaminate global variables
      • If the scope of a variable in a module cannot be (global scope), it can be solved by a function (function scope).
      • What do you mean by not contaminating global variables?
        • That is, the variables in the module cannot override the global variables, thus affecting the global variables
    • Avoid using functions directly. Function names pollute global variables
    • Modularity of IIFE implementations, which rely on other modules, can be solved by passing parameters
    • The method and variable that the module needs to expose can be mounted on the window =>Weighing the global variable contamination problem can be avoided by using special notation
Modularization with IIFE(immediate call function expression) needs to be solved: (1) Variables defined in each module cannot be modified outside the module, can only be modified within the module, then each module needs to form a separate scope (2) variables in the module can not pollute global variables => cannot be in the same scope, using the function can be solved ------ before the above problems are solved module: <! DOCTYPE html> <html lang="en"> <head> <script> var me = 'changeMe'; // changeMe </script> <script SRC ="./home. Js "></script> <! -- var home = 'chongqing' --> <script src="./me.js"></script> <! -- var me = 'woow_wu7' --> <script src="./map.js"></script> <! -- var map = 'baidu' --> </head> <body> <script> console.log(window.me, 'global variable modified window.me') // 'woow_wu7' indicates that global variable console.log(map, // baidu var map = 'Amap' console.log(map, </script> </body> </ HTML > ------ IIFE implemented modularism: <! DOCTYPE html> <html lang="en"> <head> <script> (function(window,$) { var me = 'changeMe'; Console. Log (me) // changeMe window.me = me})(window, jquery) </script> </head> <body> <script> console.log(me, 'not externally accessible, </script> </body> </ HTML >Copy the code

(4) the CommonJS specification

  • Nodejs uses the CommonJS specification and is mainly used on the server and is loaded synchronously
  • Synchronous loading
    • Nodejs is mainly used on the server, and the module files are generally stored on the disk, so the loading is faster than the asynchronous loading mode is not considered
    • But in a browser environment, to load modules from the server, you have to do it asynchronously, hence the AMD CMD scheme
  • Module indicates the current module, module.exports are external interfaces, and require a module to load the module.exports attribute
    • Note: what is the difference between mouds. exports and exports in node.js?
-- exports -- const a = 11; Module. Exports = a -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the module. The module exports exposure - modu2. Js - const b = 22. Exports. BVar = b -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - exports exposure module - index. The js - const a = the require (". / modu. Js') -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the require the introduction of module const b = the require (". / modu2. Js'). The console log (a, 'a') / / 11. The console log (b, 'b') // { bVar: 22 } console.log(b.bVar, 'b.bVar') // 22Copy the code

Amd-asynchronous Module Definition // RequireJS

  • AMD for browser side, asynchronous loading, dependent front-loading
  • The Browser side cannot use the CommonJS synchronous loading scheme
    • Because the js file loaded by the browser side is on the server, it takes a long time, and synchronous loading will block the page loading and rendering
    • On the server side, the files are on the hard disk, loading and reading are very fast, so you can load them synchronously, no matter how you load them
  • RequireJS
RequireJS (1) Directory structure: C: │ index. The HTML │ └ ─ requirejs b.j s SAN Antonio s (2) the example b.j s define (function () {/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- define (function () {... }) to define a module return 'string b}) SAN Antonio s define ([]'. / b.j s', function (res) {/ / - define (' a '], function (res) {... }) return res + 'c'}); index.html <! DOCTYPE HTML > < HTML lang = "en" > < head > < script SRC = "https://cdn.bootcss.com/require.js/2.3.6/require.min.js" > < / script > </head> <body> <script> require(['./requirejs/c.js'], function(res) {// introduce the module and use the values that the module exposes, Console. log(res, 'res')}) </script> </body> </ HTML >Copy the code

(6) Cmd-common Module Definition // seajs

  • CMD is used on the browser side, and is loaded asynchronously, relying on proximity, even when it is needed
  • CMD is the normalized output of the SeaJS module definition in the promotion process
Define (function(require, exports,)) Module){var value = 1 exports. XXX = value module.exports = value}) Module){var module2 = require('./module1') // Introduce dependency modules (synchronization) require.async('./module2', }) exports. XXX = value; // exports. XXX = value; // exports. XXX = value; Module. exports}) define(function (require) {var a = require('./module1') var b = require('./module2')})Copy the code

(7) Module scheme in ES6

  • ES6’s modular solution is a generic solution that can be used on both the browser and server side
  • The modular scheme in ES6, the design idea is static, that is, at compile time can determine the module dependency, input variables, output variables; CommonJS and AMD and CMD both determine dependencies, inputs and outputs only at run time
    • The CommonJS module is an object, and you must look for object properties on input
  • CommonJS is a runtime load, because only the runtime can generate the object, get the object, and access the value of the object
  • ES6 modules are not objects, but rather code that displays output through exports and input through imports
  • The ES6 module is in strict mode by default
// CommonJS module let {stat, exists, readFile} = require('fs'); (1) Load the fs module as a whole, and then read stat, exists and other properties from the FS object. (2) Load the fs object as a runtime load, such as CommonJS. // ES6 module import {stat, exists, readFile} from 'fs'; (2) ES6 is loaded at compile time, and does not need to be loaded at runtime like CommonJS, AMD, and CMD, so it is more efficient - this makes it impossible to refer to the ES6 module itself. Because it is not an object // the benefits of an ES6 module are (1) static loading, compile-time loading ----- is more efficient, and can be implemented (type checking) and other functions that can only be implemented (static analysis) (2) no longer need (object) as (namespace), these functions can be provided through the module in the futureCopy the code
  • The export command
    • The function of a module consists mainly of two commands: import and export
    • Export can output variables, functions, and classes
    • The output variable of export is the original name of the variable, but can be renamed using the as keyword
// Export 1; Var m = 1; export m; // export var m = 1; Var m = 1; export {m}; Var n = 1; export {n as m}; Function f() {} export f; Export function f() {}; Function f() {} export {f};Copy the code
  • The entire load of the module
    • In addition to specifying that an output value is loaded, you can also use a whole load.
    • That is, * specifies an object to which all output values are loaded
  • export default
    • Import needs to be up to the function name or variable name, otherwise it cannot be loaded. -export default specifies the default output of the module
    • Export default actually prints the variable default, so it cannot be followed by a variable declaration
// Correct export var a = 1; Var a = 1; export default a; ----------------> export default a: export default var a = 1 // correct export default 42; ---------------> Note: the value can be assigned to the default variable, the external interface is default // error export 42; -----------------------> No external interface is specifiedCopy the code
  • A combination of export and import
export { foo, bar } from 'my_module'; // Import {foo, bar} from 'my_module'; export { foo, bar };Copy the code

Import () function – supports dynamic module loading

  • Because the ES6 modular solution is statically loaded, that is, dependencies, inputs and outputs are determined at compile time; Don’t wait until run time
  • So how do you do dynamic loading?
  • Import (specifier) ———- specifier: specifier
  • Import () returns a promise
    • Import () is similar to Node’s require method, except that the former is loaded asynchronously and the latter is loaded synchronously.
    • It is run time execution, which means that when this sentence is run, the specified module is loaded.
Import () syntax (1) load on demand: load a module when needed (2) Conditional loading: different modules can be loaded according to different conditions, such as in an if statement (3) Dynamic module path: allows module paths to dynamically generate import(f()).then(...) ; // Load different modules based on the return value of function f(). (4) Import () After the module is successfully loaded, the module is treated as an object as an argument to the then method. // Therefore, you can use the syntax of object destruct assignment to get the output interface. // import('./myModule.js').then(({export1, export2}) => {... }); (5) If the module has a default output interface, it can be obtained directly with parameters. // import('./myModule.js').then(myModule => {console.log(myModule.default)}); // The myModule module has the defalut interface, All ([import('./module1.js'), import('./module2.js')), Import ('. / module3. Js'),]), then (([module1, module2, module3]) = > {...});Copy the code

data

Detailed (modularized) really well written: juejin.cn/post/684490… Ultra complete (modular) : juejin.cn/post/684490… What can’t omit semicolon in js: blog.csdn.net/BigDreamer_… ES6 modular solution: es6.ruanyifeng.com/#docs/modul… My language finch: www.yuque.com/woowwu/msyq… Modularity Resources juejin.cn/post/684490…