Develop reading

Asynchronous loading js mode

The // defer attribute specifies whether script execution is deferred, Until the page loads <script type="text/javascript" SRC ="xxx.js" defer="defer"></script> // The async property states that once the loaded script is available, <script type="text/javascript" SRC ="xxx.js" async="async"></script> Parsing HTML structure loading external scripts and style files parsing and executing script code loading binary resources such as images When the page is loaded, execute window.onloadCopy the code

Static analysis

Static program analysis is a method of analyzing programs without running them.

Static analysis is the ability to determine which code is being used and which is not before you run the code.

The reason why ESM can do static analysis is because the code has been identified before the introduction of the use of libraries, CMD, AMD, CommonJS, these can be controlled by the use of statements, is changed to dynamic introduction, so there is no static analysis.

Modularity and engineering: Webpack

Webpack supports packaging of CommonJS, AMD and ESM modular specifications. Webpack processes modules into different artifacts depending on the specification.

Modularity and Engineering: Tree Shaking

Tree shaking is a term commonly used to describe the act of removing dead-code from a JavaScript context. It relies on the import and export statements in ES2015 to detect whether code modules are exported, imported, and used by JavaScript files. Tree Shaking – MDN

Simply put, Tree Shaking is a feature that relies on static analysis of ESM modules to safely remove unused parts of code at compile time (WebPack 5 also supports CommonJS).

What is a module?

A js file with processing logic, the relevant method or object export, through the import can be used

What does modularity do?

  • Avoiding naming conflicts (reducing namespace pollution)
  • Better separation, load on demand
  • Higher reusability
  • High maintainability
  • Divide and conquer (one of the biggest advantages of modularity is that you can divide up smaller modules when the logic is complex and multiple people are developing at the same time.)

ESM(ECMAScript Module)

Strict mode: Modularity is automatically strict mode

Export/Module export: specifies the interface for exporting modules

Import: Specifies the interface for importing a module

Usage scenarios: ESM can be used directly in supported browser environments, compiled/packaged on unsupported ends, and compiled into the currently widely supported require via Babel.

Loading mode: The ESM loads modules synchronously and asynchronously depending on the environment.

Advantages: Supports synchronous/asynchronous loading, simple syntax, supports module static analysis, supports circular reference

Disadvantages: Poor compatibility, many third-party libraries do not support ESM, you can see in the library esM field description support

Note: You export a reference to an object

Function foo(params) {console.log(" this is the logical code in the module ",params); } export {foo, // expose function foo as newFoo // NewFoo is a reference to foo // so there is a total export of foo and newFoo to the outside} // Method one: this is called the on-demand import method, which is now the mainstream method, TreeShaking import {foo, Import * as allFn from 'xx/module-name' import * as allFn from 'xx/module-name' export default: Export default{foo,} import allFn from 'xx/module-name' export default{foo,} import allFn from 'xx/module-name'Copy the code

CommonJS

CommonJS is mainly used by Node.js, which loads modules synchronously through require, exports.

Exports /module.exports(exports) : exposes properties and methods that need to be accessed externally.

Remember not to be confused with ES6 module,export is multiple S, export default is also different.

Require (import) : Specifies the external import interface of a module

Usage scenario: CommonJS is used on the server (such as Node.js), or can be used on the browser after being packaged using the packaging tool.

Loading method: CommonJS loads modules synchronously, caching the results for the first load and directly reading the cached results for subsequent loads.

Advantages: Require modules at any location, supporting circular dependencies

Disadvantages: Synchronous loading mode is not suitable for browser-side use requires packaging, difficult to support module static analysis

Module. exports = foo imports cosnt foo = require("foo");Copy the code

1. Why is CommonJS only for servers and not browsers?

When we need to load a module, the CommonJS specification uses const foo= require(“foo”). If foo is fine on the server, because foo must be fine on the server. It’s the fact that foo is the definitive value at run time. And then we have to request it when our browser uses this module, so this specification doesn’t really apply.

2. The difference between import and require import

Import is an ESM standard module that is called at compile time, so it must be placed at the top of the file. It is a deconstruction process. Require is an AMD specification that is introduced as a run-time call, so require can theoretically be used anywhere in the code. It’s an assignment. The result of require is an object, number, string, function, etc., and the result of require is assigned to a variable

The difference between 3.CommonJs and ESM

  1. The CommonJS module prints a copy of the value, while the ESM prints a reference to the value.
  2. CommonJS modules are loaded at run time, ESM is loaded at compile time.

AMD (Asynchronous Module Definition)

Asynchronous module definition. Mainly used in the browser, because the browser loading module is the need for asynchronous loading, if the use of synchronization, but some module loading when used when loading, waiting, the browser is dead, then this time you need to use asynchronous loading.

AMD is the canonical product of RequireJS ‘module definition in the process of popularizing it

Usage scenario: AMD is mainly used in browsers

Loading mode: AMD asynchronously loads modules without blocking browser rendering, AMD promotes the dependency front “for the dependent module AMD is executed in advance”, each loading a module is actually loading the corresponding JS file.

Advantages: Dependency on asynchronous loading, faster startup speed, support for cyclic dependency, support for plug-ins

Disadvantages: relatively complex syntax, dependent loader, difficult to support module static analysis

/** * define * @param name * @param dependencies */ define(id) : string, dependencies? : string[], factory: Function | Object); define("alpha", ["require", "exports", "beta"], function (require, exports, beta) { exports.verb = function() { // return beta.verb(); //Or: return require("beta").verb(); }}); Require (["alpha"], function (exports) {// rely on console. Log (exports. Verb ()); });Copy the code

CMD( Common Module Definition )

CMD, the generic module definition. CMD is the standardized product of module definition in the promotion process of sea-js. CMD advocates dependence on nearby, while CMD is delayed execution, which is mainly used in the browser.

Advantages: dependency asynchronous loading, faster startup speed, support for cyclic dependency, dependency nearby

Disadvantages: relatively complex syntax, dependent loader, difficult to support module static analysis

/** * define * @param name * @param dependencies */ define(id) : string, dependencies? : string[], factory: Function | Object); Define ('hello', ['jquery'], function(require, exports, module) {// module code}); define(function (require, exports) { const hello = require("hello"); });Copy the code

UMD (Universal Module Definition)

UMD, common module definition. UMD is a cross-platform solution designed to solve the problem of common code under CommonJS and AMD specifications. It also supports module mounting globally.

AMD browser first principle develops asynchronous loading modules.

The CommonJS module follows the server first principle of synchronous loading and does not require unwrapped modules.

This forced people to come up with another, more generic pattern, UMD (Universal Module Definition). Looking for a cross-platform solution.

UMD determines whether any module (exports) that supports Node.js exists and uses node.js module mode if it does.

Check whether AMD is supported (define exists). If AMD exists, load modules in AMD mode.

Usage scenario: UMD can be used on both the server and the browser.

Loading mode: The UMD loading mode depends on the environment, node. js loading synchronously, browser loading asynchronously.

Advantages: Cross-platform compatibility

Disadvantages: Large amount of code

(function (window, factory) {
   if (typeof exports === 'object') {
      module.exports = factory();
   } else if (typeof define === 'function' && define.amd) {
      define(factory);
   } else {
      window.eventUtil = factory();
   }
})(this, function () {
   //module ...
});
Copy the code

If you don’t understand anything, or if there are any inadequacies or mistakes in my article, please point them out in the comments section. Thank you for reading.

reference