The Frontend Foundation: A Full-Stack Map from JS Closures to Browser Rendering
Frontend Knowledge System Overview
1. Functional Programming
1.1 Core Feature: Immutability
- Data cannot be changed. React's state and reducer must follow this principle; simplifying operations requires tools like immer.
- Why use it: Because data is immutable, you need to copy to create new objects; copying and updating complex objects is tedious, so utility libraries simplify it.
- Advantages: Predictable, testable, maintainable, deterministic; React internally uses shallow comparison (reference comparison), and direct mutation will cause rendering anomalies.
1.2 Pure Functions
- Definition: Given the same input, always produce the same output, with no side effects (no operations unrelated to the function's purpose, like modifying external variables).
- Notes: Do not casually introduce global variables, do not introduce mutable data, ensure determinism as much as possible.
- Value: Solves testability and maintainability, ensures determinism in engineering.
- Related applications: React pure functions, reducers need to be mastered.
1.3 Related Utility Libraries
- lodash (must master)
- immer
- date-fns
1.4 Unidirectional Data Flow
- Data flow is single and controllable: props are read-only, can only be passed from parent to child and changed, unless a change function is passed in via a callback.
1.5 Composition over Inheritance
- Generally, composition is better than inheritance.
- Single responsibility, low coupling.
- Inheritance: High coupling, changes in the parent class may affect all other subclasses.
1.6 Higher-Order Functions
- The essence is the decorator pattern.
- Definition: Takes a function as an argument or returns a function.
- Application scenarios:
- Chaining calls
- Partial application
- Currying
- Compose / middleware pattern
- Decorators
1.7 Declarative Style
2. What Happens When You Enter a URL
2.1 URL Parsing
- Purpose: Path completion, detection, caching, to facilitate subsequent domain name resolution.
2.2 Domain Name Resolution (DNS)
- Recursive query
- Iterative query
2.3 Network Transmission Layers
- Application Layer: Starts HTTP transmission, first establishes a connection.
- Transport Layer: Establishes a connection via TCP, through a three-way handshake.
- Network Layer: IP protocol, addressing, finding the unique MAC address.
- Data Link Layer
- Physical Layer
2.4 Browser Rendering
- DOM tree construction
- CSSOM tree construction
- Render tree construction
- Layout (Reflow): Calculates position and other information.
- Paint: Draws the visual layers.
- Compositing: Sends the above information to the GPU compositing layer for screen display.
3. Cross-Tab Communication
3.1 Problem Solved
Solves communication issues between tabs of the same or different origins.
3.2 Technology Selection
- localStorage
- Same origin only.
- Limited capacity, can only store strings.
- BroadcastChannel
- Same origin only.
- The current tab can be broadcast to.
- Supports multiple formats like objects.
- Usage is similar to postMessage: send with
postMessage, listen withmessage. - Larger capacity, depends on browser memory usage.
- postMessage
- Supports cross-origin. When using iframes in a project, choose based on simplicity, efficiency, and cross-origin needs.
- Pay attention to data serialization and performance issues.
- SharedWorker
- A thread that can be shared by multiple tabs.
- Compared to Web Worker, which can only be used in the current tab.
- Can be used for computation optimization.
4. Web Worker
4.1 Why Use Web Worker
- Belongs to the multi-threading API.
- The browser allows opening a thread to run independently, not blocking the main thread.
4.2 Purpose
- Solves main thread blocking issues.
- Improves performance.
4.3 Application Scenarios
- Compute-intensive: Such as large data calculations, graphics processing; business scenarios with lots of secondary data processing or specific algorithm processing, to speed up first-screen rendering.
- File upload/export scenarios: For financial business with many table data scenarios, frontend exporting tables itself consumes significant memory and time.
- Subscribing to many real-time quotes: First-screen loading needs to process a lot of real-time data.
4.4 Drawbacks
- Cannot access global variables or the DOM.
5. Browser Storage
5.1 Cookie
- Automatically carried with requests, contains a small amount of server data.
- Used for user state related content.
- Related attributes:
- SameSite: Prevents Cross-Site Request Forgery (XSRF), prohibits cross-site carrying; can be combined with double token verification for XSRF.
- Strict: Strict mode.
- maxAge: Expiration time.
- domain: Restricts/allows access from other subdomains.
- path: Restricts path access on the same domain.
- HttpOnly: Prevents XSS.
- Secure: Only carried over HTTPS.
5.2 localStorage
- Capacity: 5-10MB.
- Lifecycle: Permanent, in practice TTL expiration control is added.
- Supports same-origin sharing, can listen for changes via the
storageevent. - Applicable scenarios: Small amount of API caching (with TTL) and user configuration information, to improve user experience.
5.3 IndexedDB (Asynchronous)
- Database-level storage, asynchronous, large capacity, supports storing multiple types of content.
- Applicable scenarios: When needing to store large content like documents, images.
5.4 sessionStorage
- Capacity: 5-10MB.
- Lifecycle: Disappears when the browser tab is closed.
- Only available on the same origin.
5.5 Token vs. Session
- Session is stored on the server, cookie is stored in the browser.
- Session relies on cookies, has CSRF risk; token is placed in request headers, more secure.
- Token supports cross-origin, session is same-origin only.
5.6 Related Questions
- Why are cookie requests carried in CSRF? Aren't they different origins?
- How to prevent CSRF?
6. Cross-Origin
6.1 Essence
Browser security restriction to ensure safety, prohibiting scripts from different origins from interacting; same origin requires protocol, port, and domain to be exactly the same.
6.2 Solution Strategies
- JSONP
- Simple.
- Only supports GET requests, difficult to handle complex data, has security attack risks (callback injection).
- CORS
- OPTIONS preflight request: Complex requests (PUT, DELETE, carrying complex request headers) will send a preflight first.
- Request headers:
- Origin: Identifies the request source.
- Access-Control-Request-Method / Headers: Informs the server of the request method and headers.
- Response headers: Server returns Access-Control-Allow-Origin / Headers, etc.
- Browser determines whether to allow cross-origin.
- Carrying cookies: Set via the
credentialsfield.- sameOrigin: Only carry for same origin.
- omit: Do not carry for cross-origin.
- include: Force carry for all.
7. Frontend Security
7.1 XSS (Cross-Site Scripting)
- Essence: Injecting malicious scripts into the browser and executing them.
- Classification:
- Reflected: Inject script into the path, when accessed, information is stolen and sent to the server.
- Stored: Malicious script is stored on the server.
- DOM-based: Dangerous script is injected into innerHTML via JS and executed.
- Prevention:
- Input/output escaping: Through dompurify, or direct escaping.
- Convert to Markdown: In AI projects, as a fallback, escape first via markdown-it.
- Set the HttpOnly attribute for cookies to prevent JS reading.
- CSP protection: Set request headers to control resource loading, avoiding inline and illegal resource loading.
7.2 XSRF/CSRF (Cross-Site Request Forgery)
- Principle: When a user is logged in, clicking an attack page sends a forged request to the target website.
- Essence: Exploits the feature that cookies are automatically carried in requests to the target domain.
- Prevention:
- Double token verification: Exploits cross-origin restrictions, attackers cannot get specific cookie content.
- SameSite: Only same-site can carry cookies.
- CAPTCHA.
7.3 Other Attacks
- Clickjacking: Prohibit iframe embedding via X-Frame-Options (deny, allow, etc.), set whitelist links via CSP.
- DDoS attacks.
- Man-in-the-middle attacks, etc.
8. Frontend Engineering
8.1 What is Engineering
A set of software engineering processes, including development, testing, optimization, deployment, monitoring, CI/CD, and other systematic engineering.
- Problem solved: Reduces development costs, improves engineering efficiency, as well as scalability, stability, etc.
8.2 Modularization
- Core idea: Layered decoupling.
- Differences between CommonJS and ES Modules:
- CommonJS: Synchronous, dynamically loads modules, exports a copy of the value; exports via
module.exports, imports viarequire. - ES Modules: Static loading (dependency relationships determined at compile time), supports Tree-Shaking, exports a reference; exports via
export/export default, imports viaimport.
- CommonJS: Synchronous, dynamically loads modules, exports a copy of the value; exports via
- Using ES Modules in Node.js: File extension
.mjs, or specifytypefield asmoduleinpackage.json. - Circular dependency differences (low-frequency exam topic).
8.3 Webpack
- What it is: A static module bundler.
- Problem solved: Solves browser compatibility issues and performance optimization issues.
- Core concepts:
- entry: Entry point.
- output: Output.
- loader: File transformation.
- CSS related: style-loader, css-loader.
- JS related: babel-loader.
- thread-loader: Enables multi-threading.
- plugin: Plugins, handle the entire build process.
- module: Single file module.
- chunk: Composed of multiple modules, split according to package update frequency.
- bundle: Final file output.
- Build process:
- Initialization phase: Reads configuration, initializes the compiler object (manages configuration, plugins, lifecycle); registers plugins (plugins implement this by passing the compiler object to the
applyfunction). - Compilation phase: Analyzes the dependency graph based on the entry file; when encountering a module file, uses loaders to transform it, generating an AST; cooperates with optimizations like code splitting; finally generates chunks.
- Output phase: Generates bundle files according to output configuration.
- Initialization phase: Reads configuration, initializes the compiler object (manages configuration, plugins, lifecycle); registers plugins (plugins implement this by passing the compiler object to the
- Related questions:
- Tree-Shaking principle, applicable scenarios.
- How to speed up compilation.
- Which phase does multi-threading optimization belong to?
- Difference between loader and plugin:
- loader: A function, transforms single file content (e.g., markdown to html, babel-loader, ts-loader, css-loader).
- plugin: Solves file-system-level problems, as loaders can only handle single files; executes by listening to lifecycle hooks via tapable.
8.4 Vite
- Cold start: Compared to webpack, directly utilizes native browser ES Module parsing capabilities, bypassing compilation and bundling, compiling accessed files on demand.
- Pre-bundling: Pre-bundles node_modules in advance, processing in parallel; uses esbuild (a bundler written in Go) for multi-threaded bundling, merging multiple files and entry points.
- Purpose of pre-bundling: 1. Convert CommonJS to ES format; 2. Merge requests to reduce the number of requests.
8.5 Package Management Tools
- npm: Good compatibility, but flattens dependencies, leading to duplicate downloads and phantom dependency issues (packages hoisted to the root directory).
- yarn: Supports parallel downloads, caching mechanism.
- pnpm: Tree-like dependency structure, no phantom dependencies, no duplicate packages; reduces duplicate package loading through symbolic links/hard links.
8.6 Monorepo
- Multi-package management solution: Solves dependency governance, code reuse, and team collaboration problems; a single repository, unified management of dependencies and publishing.
8.7 Turbopack: Just understand it.
8.8 CI/CD
- Continuous Integration and Deployment: Code commit → Automatic build → Automatic test → Deploy online.
- Docker: Ensures environment consistency and isolation, just understand it.
8.9 Testing
- Utility functions: Jest.
- Component level: React Testing Library.
- E2E: End-to-end testing, covering complete flows.
9. JavaScript Core Fundamentals
9.1 Data Types
- 8 types in total
- Primitive types: Symbol, String, Boolean, BigInt, null, undefined, Number.
- Reference type: Object.
- Difference between primitive and reference types.
- How to prevent modification: Shallow copy, deep copy.
- Shallow copy: Only copies the first level, nested objects only copy the address, cannot fully isolate.
- Implementation methods: Object.assign, spread operator, array-specific (slice, concat).
- Deep copy: Recursive processing, generates a completely independent copy.
- JSON.stringify method: Cannot handle circular references, functions, abnormal values.
- Shallow copy: Only copies the first level, nested objects only copy the address, cannot fully isolate.
- Engineering application: In React, immer's underlying logic is based on shallow comparison and pure function concepts, returning new objects to simplify immutable data operations.
- Shallow comparison: For performance balance, avoids deep comparison of large objects.
- Stack and Heap:
- Primitive data types are stored on the stack, reference types on the heap.
- Stack stores copies of values, heap stores references to values.
- Primitive types are immutable, reference types are mutable.
- Reason for storing primitives on the stack: Stack structure is simple, space is limited, improves query efficiency; heap stores reference types, structure is complex, memory supports dynamic changes, adapts to complex types.
9.2 Type Checking
- typeof: Can check primitive data types, cannot finely check reference types;
typeof nullisobject(early JS design flaw: null was represented with all-zero bits, object also used a zero identifier, leading to misjudgment). - instanceof: Cannot accurately check all reference types, cannot check primitive types; judges via the prototype chain mechanism.
- Object.prototype.toString.call: Most accurate.
- Array.isArray: Specifically checks for arrays.
9.3 Floating-Point Precision Issue
- 0.1 + 0.2 !== 0.3
- Reason: IEEE 754 standard, computers perform binary conversion, decimal points suffer precision truncation.
- Structure: 1 sign bit, 11 exponent bits, 52 mantissa bits.
- Maximum safe integer: 2^53 - 1; the -1 is to prevent precision overflow, 53 bits includes a leading 1.
- BigInt: Can safely represent values exceeding 2^53 - 1.
9.4 Symbol
- Uses: Simulating private variables, resolving naming conflicts, commonly used in engineering collaboration.
- Symbol.iterator: Iterator, used to deploy iterable objects.
9.5 Event Loop
- What it is: An event management mechanism for scheduling asynchronous tasks.
- Background: Addresses the blocking phenomenon caused by asynchronous tasks, given JS's single-threaded nature.
- Composition:
- Call Stack: Pushes and executes synchronous tasks.
- Macro Tasks: Timers, event listeners, UI rendering, MessageChannel; MessageChannel is used for React's internal scheduling, replacing requestIdleCallback; initiated by the host environment (browser, Node).
- Micro Tasks: Initiated by the JS engine API; includes Promise.then/catch/finally, MutationObserver, queueMicrotask, process.nextTick (highest priority in Node).
- Web APIs.
- Execution order explanation:
- Execute synchronous code first, then clear the microtask queue, then execute one macro task, then clear microtasks again.
- requestAnimationFrame execution timing: After microtasks, before the next macro task.
- Difference between browser and Node event loops:
- Browser: Clears the microtask queue after each macro task execution.
- Node: Microtask queue is cleared after each phase; macro task queue is executed in batches, not individually.
- Example: Two setTimeout callbacks both enter the Timers macro task queue, execution order is: Timer 1 executes → Timer 2 executes → Microtask 1 → Microtask 2.
- Underlying difference: Browser is driven by the browser kernel, Node is driven by the underlying libuv library.
- Node has no UI rendering, has the highest priority process.nextTick.
9.6 Scope and Closures
- What is scope: The range and rules where variables are effective.
- Lexical scope: Scope is determined by where the code is defined, not where it is called.
- Classification:
- Global scope.
- Local scope.
- Function scope.
- Block scope.
- Function scope traps in React: Need to use functional updates, useEffect to solve.
- Scope chain: Chained nested structure, a mechanism for looking up variables in outer scopes.
- Engineering application: Webpack scope hoisting, avoids inefficiency of nested scope lookups.
- Hoisting: An early JS code fault-tolerance mechanism, pre-parses early to improve efficiency, but affects engineering standards; later introduction of let, const formed the Temporal Dead Zone, not allowing access before declaration, requiring definition before access.
- Closures:
- Definition: Under lexical scope, a function that references free variables from an outer local scope; the combination of the two is a closure.
- Note: Simply referencing a global variable is not a closure; one value of closures is extending the lifecycle of a local scope, global variables themselves don't need closures.
- Application scenarios: Caching, debounce/throttle, variable privatization, partial application, modularization (IIFE).
- Problems caused by closures: Referenced local variables are not destroyed, causing memory leaks; e.g., timers not cleared.
- Solutions: Disconnect references promptly, use WeakMap for weak references, clear timers promptly when components unmount.
- WeakMap:
- Keys can only be objects.
- Not iterable, key-value pairs can be garbage collected at any time.
- Weak reference characteristic.
9.7 this Binding
- What it is: A dynamic context injection mechanism.
- Binding methods: call, apply, bind (explicit binding), implicit binding.
- Binding priority:
- new binding: Highest priority, other binding rules become invalid;
thisalways points to the instance object. - Explicit binding: call, apply, bind.
- Implicit binding: Whoever calls it,
thispoints to them. - Default binding: When called standalone, defaults to
window.
- new binding: Highest priority, other binding rules become invalid;
- Arrow functions:
thisis always thethisof the outer lexical scope.- No prototype object.
- Cannot be used as a constructor.
- Cannot use the
newoperator. - No
argumentsobject, can use rest parameters instead.
thisloss scenarios:- Timers: Callback is called standalone, defaults to
window. - forEach, map: Callbacks are called standalone, default to
window; can be solved by passing athisargument. - Event listener functions: Regular functions point to the target DOM object (internally auto-bound); arrow functions inherit the outer scope's
this.
- Timers: Callback is called standalone, defaults to
- Special rule in inheritance scenarios: After
super()call, the parent constructor'sthispoints to the subclass instance object.
9.8 Prototype and Prototype Chain
- What is a prototype: The prototype pattern is used to implement inheritance; structurally, it's an object, the constructor's
prototypepoints to the prototype object. - Function: Enables property and method reuse through prototype chain lookup.
- Inheritance implementation methods: Prototypal inheritance, combination inheritance, parasitic inheritance, parasitic combination inheritance, ES6 class.
- Drawbacks: Prototype pollution (overwriting properties/methods on the prototype chain).
- Avoidance methods: Standards and ESLint prohibit overwriting prototypes; use Object.create(null), Map.
- Map: Keys are stored independently, does not query the prototype chain.
- hasOwnProperty: Checks for own properties.
- Object.create(null): Creates a pure object without a prototype chain, avoiding prototype chain interference.
- Related question: How to determine a pure object? 1. Whether
__proto__points to null (Object.create(null)); 2. Whether the implicit prototype's constructor points to the Object constructor.
9.9 Asynchronous Programming
- Value: Solves non-blocking thread issues, breaks through single-threaded language limitations.
- Evolution: Callback Hell → Promise → Generator → async/await.
- Promise:
- Feature: Once the state changes, it is absolutely irreversible.
- Three states: pending, fulfilled, rejected.
- Instance methods: then, catch, finally.
- Static methods: all, race, allSettled, any, resolve, reject.
- Cancellation methods: Use a flag, AbortController.
- Generator.
- async/await:
- Rule: If an async function returns a plain value, it will be wrapped by Promise.resolve; if it's a Promise object, it is returned directly.
- Principle: Relies on Promise plus Generator + automatic next execution.
9.10 ES6 Features
- Differences between var, let, const.
- Symbol / BigInt.
- Map, Set, WeakMap: Hash table structure, O(1) query operations; WeakMap solves memory leak issues caused by Map through weak references.
- Destructuring, spread operator: Commonly used to simplify value extraction.
- Arrow functions: Simplifies function syntax, pay attention to
thisbinding issues.
10. TypeScript
10.1 What is TS
- A superset of JS, a statically typed language.
- Problem solved: Solves the issue of JS's dynamic typing where type errors are only found at runtime (the number one JS error is type-related).
- Improves project readability and robustness.
- Essence: Implements a compiler using TS.
10.2 Compilation Principle
- Parse TS: Lexical analysis, syntax analysis.
- Type checking: Checks if types are standard, reports errors if not.
- Code generation: Removes all type content and transpiles, outputting browser-recognizable JS.
10.3 Common Types
- 8 basic data types.
- Tuple: Solves scenarios where array elements have different types.
- Enum:
- Fields are more semantic and extensible; numeric enums support reverse mapping.
- enum: Generates a complete object at compile time, iterable, supports reverse mapping.
- const enum: Does not generate an object at compile time, directly returns the value at runtime, not iterable.
- Union types: Type has multiple possibilities.
- Intersection types: Achieves effects similar to type inheritance.
- any, unknown (type-safe any), never (when throwing errors, absolutely no return value scenarios), void (function has no return value).
- type alias: Can define any type alias, improving maintainability; achieves reuse and semantics.
- Difference between type and interface:
- type uses intersection types for extension, interface uses extends.
- type supports any type alias, interface only supports objects and functions.
- type focuses on any type alias, interface focuses on objects and inheritance.
- as type assertion:
- Essence: Specifies a concrete type at compile time.
- Uses: Restore type judgment for any, unknown types; narrow types for union types.
- Generics: Improves extensibility.
- Classification: Function generics, class generics, parameter generics, interface generics.
- Generic constraints: Constrain and narrow generics using extends.
- Covariance and Contravariance:
- Covariance: Subtypes can be assigned to parent types.
- Contravariance: Parent types can be assigned to subtypes.
11. React
11.1 What is React
- A UI library driven by data (state/props change → reconcile → calculate minimal changes → DOM update → UI change).
- Core ideas: Functional programming, strict unidirectional data flow, declarative style, JSX for describing UI, componentization (for decoupling and reuse).
11.2 Fiber
- What it is:
- Data structure level: A linked list structure, containing component information, priority, pointers.
- Why linked list: Through pointer references, facilitates interruption and resumption of execution.
- Structure:
- type: Node type.
- memorizedState: Current state.
- child: Child node pointer.
- sibling: Sibling node pointer.
- return: Parent node pointer.
- alternate: Points to the workInProgress tree.
- key: Node identifier.
- Algorithm level: Reconciliation algorithm, through priority scheduling, time slicing, double buffering tree diff comparison.
- Double Buffering Tree:
- Advantages: Ensures UI consistency, no intermediate states; supports interruption and resumption.
- Implements mutual pointing and alternating rotation of double buffering trees via alternate.
- Time Slicing:
- Tasks are split into 5ms units.
- Checks if the current frame has idle time, yields control if timeout, executes the next fiber unit.
- Each time points to the current fiber unit, checks if timeout; if timeout, saves the next work unit, returns after execution.
- Cooperates with the macro task MessageChannel to simulate time window scheduling.
- Work Loop:
- Loops through fiber tasks (Depth-First Search DFS).
- Before each execution, checks if the current frame has idle time: if yes, continues the loop; if no, breaks the loop and saves the work unit, continues next time.
- Problems solved:
- Solves the synchronous update blocking issue in React 15 and earlier (root cause is JS being single-threaded).
- Goal: Achieve interruptible and resumable updates, support concurrent features (scheduling, time slicing, reconciliation algorithm, etc.).
11.3 Reconciliation and Commit
- Reconciliation Phase (Reconcile)
- beginWork: Processes the current fiber node, calculates new workInProgress based on props and state; performs diff comparison, tags at the same level (add, delete, update).
- completeWork: Based on the updated fiber tree, creates/updates DOM nodes, does not insert immediately.
- Cooperates with Scheduler to achieve task scheduling, time slicing, and reconciliation diff.
- Commit Phase (Commit)
- Synchronous update, cannot be interrupted.
- beforeMutation: Schedules useEffect, executed before DOM operations.
- mutation: Executes DOM update operations based on tags from the reconciliation phase diff.
- layout: Executes useLayoutEffect, updates refs.
- Responsibility: Synchronizes side effects to the DOM, and triggers useLayoutEffect and useEffect sequentially.
11.4 Priority Scheduling
- Scheduled via Scheduler.
- Priority assigned via the Lane model.
- When a high priority task arrives, it re-executes the render logic, discarding the ongoing workInProgress build.
- Lane model: Based on bitwise operations, efficient; can have multiple priorities simultaneously, facilitating complex scheduling.
- Scheduler + Lane model + interruptible render together achieve concurrent updates.
- Why not use requestIdleCallback: Poor compatibility, and cannot achieve fine-grained scheduling.
- Simulated via MessageChannel macro task: Executes in the next event loop, does not block browser rendering.
11.5 Diff Algorithm
- What it is: Reconciliation comparison algorithm, finds the minimal difference update, ensures minimal DOM operations, reduces reflows.
- Three strategies:
- Element key comparison: Loop lists compared via key.
- Component level comparison: Different types (e.g., div to span) directly delete and rebuild.
- Tree level comparison: Inconsistent nodes at the same level, all child nodes are deleted and rebuilt.
- Low time complexity.
- Classification:
- Single node comparison: Compare one by one, mark side effects; check both key and type.
- Multi-node comparison: Two rounds of traversal, first round finds reusable nodes, second round handles movement; if new nodes are exhausted and old nodes remain, delete; if new nodes remain and old nodes are exhausted, create.
- Role of key: Used for node reuse during the diff process.
- Drawbacks of random/non-unique keys: Leads to reuse errors and state errors.
11.6 Hooks
- What they are: An embodiment of functional programming, solves the problem of function components being stateless.
- Essence: Represents the composition pattern in functional programming, generally better than inheritance in regular scenarios, solves encapsulation and extension problems in engineering.
- Why they cannot be used in conditional statements:
- Hooks determine the call order at compile time through the next pointer of linked list nodes.
- During updates, they execute updates sequentially according to the defined hooks call order.
- If the order changes at runtime, it leads to state update errors and rendering anomalies.
- useState flow:
- Creates a hook linked list, memorizedState stores the state value.
- Initializes the state value.
- Maintains an update queue, next points to the next hook.
- set method: Triggers pushing to the update queue, batch execution.
- Render phase: Based on the update queue, updates state in linked list order, returns new value and setter.
- useEffect:
- Schedules useEffect in the beforeMutation phase.
- Executes the useEffect callback asynchronously after paint.
- Initialization creates an effect object, containing deps, execution callback, cleanup function, next pointer.
- On update, reads old dependencies from memorizedState, performs shallow comparison with new dependencies.
- Execution order: Immediately executes the cleanup function first, then executes the internal callback.
- Custom Hooks.
- useImperativeHandle applicable scenarios.
11.7 Synthetic Events
- What they are: React's own simulation of the browser event mechanism, mainly handles event bubbling, centrally delegates event listeners.
- Why synthetic events:
- Shields browser compatibility differences.
- Strong controllability, easy to schedule.
- Integrates with Fiber, supports interruptible handling.
- Principle:
- Events are delegated to the root node (React 17 and later delegate to the root container, 16 and earlier to document).
- Improves performance, reduces memory usage; facilitates coexistence of multiple React versions, isolated from each other.
- Execution order:
- Native events execute first, synthetic events execute later during the bubbling phase at the root.
- After native event capture and bubbling are complete, synthetic event bubbling executes.
- Native event's e.stopPropagation cannot stop synthetic events.
- Prevention methods: 1. Stop bubbling via native event e.nativeEvent; 2. Set event capture mode.
- Standard practice recommends not mixing native events and synthetic events.
11.8 Redux
- What it is: A global state management library.
- Problem solved: Re-rendering difficulties caused by deep component state sharing.
- Core principles:
- Single store: Easy to persist, unified management.
- Pure function modification: Deterministic, testable.
- Immutable data.
- Unidirectional data flow.
- react-redux:
- Function: Binds state and UI, thus driving page updates.
- Principle: Based on createStore to create a data source; defines actions to decide data processing; reducer receives the action dispatched by dispatch and returns new state; components subscribe to state changes and re-render.
- Middleware:
- Definition: Functions that enhance the dispatch functionality.
- Execution timing: After dispatch, before reaching the reducer function.
- Principle: Onion ring model, implemented via higher-order functions.
11.9 Component Lifecycle
- Mounting: constructor → componentWillMount → componentDidMount.
- Updating (triggered by props/state changes): componentWillReceiveProps → shouldComponentUpdate → componentWillUpdate → render → componentDidUpdate.
- Unmounting: componentWillUnmount.
11.10 JSX Essence
- Syntactic sugar for createElement.
- Changes to JSX transformation after React 17.
11.11 Version Differences
- Improvements in React 17 compared to 16.
- Improvements in React 18.
12. Browser Rendering
12.1 Rendering Process and Flow
- Lexical analysis: Splits characters (UTF-8) into minimal token units.
- Syntax analysis: Builds a syntax tree based on structural information.
- Builds the DOM tree.
- Builds the CSSOM tree: Processed in parallel with the DOM tree, does not block each other.
- Function: Calculates visual element styles, provides access interfaces, generates the CSS tree.
- Does not block DOM tree construction, but blocks subsequent render tree construction.
- Render Tree: Synthesized from DOM tree and CSSOM tree, blocked by CSS; only contains visible nodes, nodes with
display: noneare not included. - Layout (Reflow): Recalculates element geometric positions.
- Paint (Repaint): Redraws image pixels.
- Compositing: Merges multiple layers, GPU processes the composite image.
12.2 JS Blocking Issue
- Both DOM and CSSOM construction are blocked when encountering JS, because JS might manipulate the DOM or CSS, requiring waiting for its execution to complete.
- Reason for placing CSS in the head: Avoids blocking render tree construction.
- Difference between defer and async:
- Commonality: Both load asynchronously, do not block DOM parsing.
- defer: Execution is deferred until after loading is complete, executes after DOM parsing is complete, guarantees execution order, emphasizes dependency order.
- async: Executes immediately after loading is complete, does not guarantee order, suitable for scripts without dependencies.
12.3 Reflow and Repaint
- Reflow
- Definition: Recalculating layout.
- Trigger scenarios: Changes to element geometric properties, position information, DOM manipulation.
- How to reduce reflow:
- Batch/offline DOM operations.
- Virtual scrolling, reducing DOM count.
- Debounce/throttle.
- Promote to compositing layer (skip reflow), e.g., transform, will-change.
- Conclusion: Reflow always triggers repaint, repaint does not necessarily trigger reflow.
- Repaint
- Definition: Redrawing image pixels.
- Trigger scenarios: Changes to non-geometric properties like element color, style.
- Process: Draws node by node from background to element; rasterization converts to pixel data.
- Compositing Layer
- An independent drawing layer, processed by the GPU.
- Trigger methods: transform, opacity, will-change.
- Note: Compositing layers should not be too many.
- GPU Process: Responsible for 3D drawing, hardware acceleration.
- Plugin process, network process.
12.4 Advantages of Multi-Process Architecture
- Fully utilizes multi-core capabilities, improving efficiency.
- Divide and conquer: Ensures stability and security, prevents a single process crash from crashing the entire browser.
13. HTTP
13.1 Definition
A transfer protocol, used for data request and transmission, located at the application layer.
13.2 Differences between HTTP 1.0 and 1.1
- Connection method: 1.0 is short-lived connections, serial requests (one request, one response); 1.1 supports persistent connections, can set expiration time via
Connection: keep-alive. - Caching: 1.0 only has
expiresexpiration time; 1.1 supportsCache-Control,Etag. - Added host header, status codes, etc.
- host: Distinguishes requests for different domain names under the same IP address.
- origin: Cross-origin identifier, includes protocol, port, domain.
- referer: Request source, used for behavior monitoring and statistics.
- Common status codes: 301, 302, 304, 307.
- 307 is equivalent to a guaranteed version of 302, temporary redirect, keeps the request method consistent.
13.3 HTTP 2.0
- Multiplexing: Multiple requests concurrently, multiplexing a single TCP connection, application layer is not blocked.
- Binary framing + Stream ID mechanism: Server reassembles data via ID, does not block the application layer.
- Header compression: HPACK algorithm, maintains an index mapping table, only transmits the index, reducing transmission overhead.
13.4 HTTP 3.0
14. Performance Optimization
14.1 Performance Metrics
- TTFB (Time to First Byte)
- Optimization directions: HTTP2, server-side caching, CDN, enable keep-alive by default.
- FP (First Paint): First paint of any content.
- FCP (First Contentful Paint): First paint of text, image, canvas, etc.
- LCP (Largest Contentful Paint): Render time of the largest content element in the viewport, value changes dynamically as content changes.
- Target objects: img, background images, block-level elements containing text.
- Optimization directions: Preloading, multi-level caching, CDN, inline critical CSS, JS deferred loading (async).
- FID (First Input Delay)
- Optimization directions: Web Worker opens auxiliary threads to reduce main thread pressure; useTransition improves user operation priority; code splitting, on-demand loading to reduce JS volume.
- TTI (Time to Interactive): Technical metric, FID is closer to actual user perception.
- Measurement tools: Lighthouse, Performance Timing, PerformanceObserver, web-vitals.
- Reporting methods: Centrally report via sendBeacon / fetch compatibility.
14.2 Loading Performance Optimization
- Resource compression.
- Preload series:
- pre-dns: Early DNS resolution.
- pre-connect: Early TCP, TLS connection establishment.
- preload: Preload and execute immediately, for critical CSS, font resources.
- prefetch: Execute when idle, for non-critical above-the-fold resources.
- CDN.
- HTTP 2.0 multiplexing.
- Tree-Shaking.
- On-demand loading.
14.3 Rendering Performance Optimization
- Virtual scrolling.
- Web Worker offline computation.
- requestIdleCallback idle execution.
- Component caching like React.memo.
- Reduce reflow behaviors from direct DOM manipulation.
- Debounce and throttle.
15. Frontend Monitoring
15.1 Behavior Monitoring
- rrweb: Monitor and replay user behavior, track complete paths.
- Collection granularity: Page level, element level.
- Reporting methods: sendBeacon, fetch, img (img only has GET method, limited by browser parameters).
15.2 Performance Monitoring
- performance.timing: Records various performance metric times.
- performanceObserver: Detects performance metrics and rendering performance, more comprehensive.
- resource-timing: Resource loading time statistics.
15.3 Error Monitoring
- JS errors: Listen for the
errorevent. - Promise errors: Listen for
unhandledrejection. - Resource loading errors: Distinguish between window and resources via target.
- Request error capture, etc.
- sourceMap: Source maps for compressed files, used to locate error positions; only upload one copy to the server, not exposed to the frontend.
15.4 White Screen Detection
- Sampling detection: Check if there are key node DOM elements.
- MutationObserver detects changes in the number of body child nodes.
16. System Design
16.1 Component Library Design
- Theme system: Controlled via Context + CSS variables.
- Multi-language.
- On-demand loading: Automatically switch paths via babel-import-plugin.
- Common library: Lightweight.
- Component development: Complete TS types, standardized interfaces, make controlled components as much as possible, supporting usable documentation.
- Supporting monitoring.
16.2 File Upload Design
- Large file splitting: Split into fixed-size chunks.
- Concurrent upload: Limit concurrent uploads based on split chunks.
- Resumable upload: Record successfully uploaded chunks and their corresponding indices.
17. CSS Supplement
17.1 HTML Semantics
- Advantages: Good scalability, readability, SEO-friendly.
- Common tags: header, title, nav, main, etc.
17.2 H5 New APIs
- localStorage, WebSocket, Web Worker, Canvas, SVG.
17.3 Box Model
- Standard box model (content-box): Width and height do not include border and padding.
- IE box model (border-box): Width and height include border and padding, more intuitive, width is the actual width.
- Set via box-sizing.
17.4 BFC (Block Formatting Context)
- Definition: An independent rendering area, internal element layout does not affect external layout.
- Problems solved:
- Clear floats: After the parent element triggers BFC, internal floating elements are included in height calculation.
- Margin collapsing: Wrapping child elements avoids margin collapsing.
- Adaptive layout: Floating element + right BFC element achieves adaptive width.
- Trigger methods:
- float is not none.
- overflow: hidden (element does not overflow, triggers BFC).
- display: flex / flow-root (flow-root is specifically for generating BFC).
- Verification: Check the block identifier via computed to determine if floats are cleared, if margins overlap.
17.5 Clearing Floats
- Pseudo-element clearfix:
.clearFix::after { content: ''; display: block; clear: both; } - Principle: Adds an empty content block-level element via the after pseudo-element, sets clear: both to achieve clearing.
- Triggering BFC can also clear floats.
17.6 Flex Layout
- Container properties (parent element):
- flex-direction: row (horizontal), column (vertical).
- flex-wrap: wrap, nowrap.
- justify-content: center, space-between, space-around, flex-start, flex-end.
- align-items: center, flex-start, flex-end.
- Item properties:
- flex-grow: 0 / 1, grow ratio.
- flex-shrink: 0 / 1, shrink ratio.
- flex-basis: Initial size.
- 0%: Size completely determined by grow.
- auto: Initial size determined by own content.
18. Caching
18.1 Strong Cache and Negotiated Cache
- Strong cache: Controlled by Cache-Control's max-age.
- Negotiated cache: Validated via Etag, Last-Modified.
- Validation fields:
- If-Modified-Since: Corresponds to Last-Modified.
- If-None-Match: Corresponds to Etag.
18.2 Overall Caching Flow
- Why caching: Avoids the server resending resources for every request, improving access efficiency.
- Cacheable resources: Static resources (img, css, js).
- Not recommended to cache: HTML (structure may change with requirements).
- Strong cache flow:
- First time browser initiates HTTP request to server.
- Server returns resource, response header includes Cache-Control: max-age (resource expiration time).
- Browser stores the resource and cache identifiers (Last-Modified, Etag) in local cache.
- Second request for the resource, first accesses local resource, simultaneously checks if the resource has expired (based on Cache-Control max-age / expires).
- Not expired: Local cache directly returns the resource.
- Expired: Enters the negotiated cache flow.
- Negotiated cache flow:
- Carries the previously returned cache identifiers (Etag / Last-Modified) to send a request to the server.
- Server compares its latest identifiers with the identifiers sent by the client.
- Match: Returns 304, indicating the resource has not been updated, continue using local cache.
- Mismatch: Returns 200 and the new resource.
- Related attribute descriptions:
- expires: HTTP 1.0 field, absolute server time, has discrepancy with client time.
- Cache-Control:
- max-age: Calculates difference based on client time.
- no-cache: Does not hit strong cache, directly goes to negotiated cache.
- no-store: No caching at all, neither strong cache nor negotiated cache, requests the latest resource every time.
- public: Can be cached by proxy servers.
- private: Cannot be cached by proxy servers.
- Etag / Last-Modified:
- Etag: Server generates a unique identifier string based on content, consumes server resources; higher precision, prevents misjudgment.
- Last-Modified: Latest modification time of the resource.
- Applicable scenarios: Etag is suitable for precise validation of dynamic APIs; Last-Modified is more efficient for static resources.
19. HTTPS
19.1 What it is
Based on the HTTP protocol, relies on the TLS handshake at the lower layer to ensure transmission security.
- Solves the drawback of HTTP plaintext transmission.
- Port number 443 (HTTP is 80).
- Core features: Encryption, signature verification, digest, together ensure security.
19.2 Hybrid Encryption Mechanism
- Symmetric encryption: AES algorithm, medium security, good performance, suitable for the conversation transmission phase; balances performance and security.
- Asymmetric encryption: ECDH algorithm, high security, poor performance, suitable for the key exchange phase; ensures the transmitted key has not been altered.
19.3 TLS Handshake Process
- HTTPS 1.2: 2 RTTs
- Client: Sends version, cipher suites, random number.
- Server: Returns version, cipher suites, random number, certificate.
- Client: Verifies the certificate chain, generates a pre-master key.
- Server: After receiving, combines the three keys to generate the master key, starts encrypted communication.
- Signature verification principle: CA private key encrypts the certificate digest, client uses the public key to decrypt the digest, then compares if the certificate content has changed via the digest algorithm.
- HTTPS 1.3: 1 RTT optimization, supports 0-RTT caching optimization.
20. TCP / UDP
20.1 What is TCP
Transmission Control Protocol, solves end-to-end, connection-oriented, byte-stream reliable transmission; based on the transport layer.
20.2 Three-Way Handshake
- Client sends a connection request to TCP: SYN=1, sends seq.
- Server receives: Returns seq and an ACK based on the previous seq.
- Client: Sends ACK again, starts communication.
- Why not two-way: Two-way cannot achieve bidirectional confirmation, can be interfered with by old connections.
- Why three-way: Ensures bidirectional confirmation, avoids interference from old connection requests.
20.3 Four-Way Wave
- Sender: Sends FIN termination packet and seq.
- Receiver: Returns ACK confirmation.
- Receiver: After remaining data is sent, sends FIN termination packet and seq.
- Sender: Returns ACK confirmation, waits 2MSL before entering CLOSED state.
- Reason for waiting 2MSL: Prevents the server from not receiving the last ACK, if the server resends FIN, the client can resend ACK; ensures processing within the maximum lifecycle of both packets.
- Why four-way: Full-duplex communication requires bidirectional confirmation; the server usually has remaining data to send before ending.
20.4 TCP Features
- Connection-oriented.
- Reliability guarantee.
- Congestion control: Slow start (exponential window growth), congestion avoidance (linear growth), fast retransmit, fast recovery.
- Flow control: Prevents sender data from being too fast, ensures the server can handle it; guaranteed via the sliding window mechanism.
- Header overhead: 20 bytes.
- Applicable scenarios: HTTP, HTTPS, FTP file transfer, and all scenarios requiring accuracy and completeness.
20.5 TCP Security and Issues
- SYN flood attack: Only sends requests without confirming; prevention: limit request rate from the same IP address.
- Sticky packets and packet splitting:
- Sticky packets: TCP optimizes by merging small data packets, causing data adhesion.
- Packet splitting: Server receiving capacity is limited, splits packets if exceeded.
- Solution: Fixed packet size, add length identifier to the packet body.
20.6 UDP
- Connectionless, no reliability mechanism guarantee.
- Header overhead: 8 bytes.
- Applicable scenarios: Voice, live streaming, DNS.
21. Architecture Design and Coding Standards
21.1 MVC
- Layering:
- Model layer: Handles business logic independently.
- View layer: UI components only undertake data display, not involved in business or data processing.
- Controller layer: Involves data fetching, data formatting related tasks.
- Value: Makes the project hierarchy clear, easy to maintain.
21.2 Virtual Scrolling
- Applicable scenarios: Rendering lists with tens of thousands of data items.
- Purpose: Avoids rendering too many DOM nodes simultaneously causing lag.
- Principle (fixed height scenario):
- Determine the height of the entire visible area.
- Divide the area into upper buffer, visible area, lower buffer.
- Record user scroll distance, upper and lower boundaries of the visible area and buffer, dynamically calculate the distance of each element from the top, achieving dynamic loading.
- Implementation ideas for variable height scenarios.
21.3 Node Related
- What scenarios has Node handled?
- How to handle reading large files?