Preface
Many beginners start learning frontend by simply copying examples: memorizing tags, reciting attributes, copying components, and running scaffolds. Initially, they might manage to piece together a few pages, but as they progress, they find it increasingly difficult—they feel they understand others' examples, yet can't start from scratch themselves, and are completely lost when encountering bugs.
This is because the real difficulty often isn't 'not being able to write code,' but 'not understanding the code.'
Try asking yourself these questions:
- Why does a page display after entering a URL?
- What exactly happens to HTML, CSS, and JS inside the browser?
- Why do reflow and repaint occur?
- Why does
thissometimes point to something strange? - Why does
Promise.thenexecute beforesetTimeout? - Why can Vue's
nextTickaccess the updated DOM? - Why shouldn't the
keyin React be assigned carelessly? - Why does the build process become frustratingly slow as a project grows?
These questions seem scattered, but behind them lies a complete and rigorous web frontend knowledge system. Frontend development is an engineering practice composed of multiple interconnected threads: browsers, network protocols, language mechanisms, page rendering, engineering practices, framework philosophies, and performance optimization.
This article aims to help you break free from the dilemma of 'not seeing the forest for the trees.' I will try to connect the core underlying threads of frontend from shallow to deep, guiding you to re-understand what frontend truly is.
I. What Does Frontend Actually Do?
1. What is the Web?
The Web is essentially a system for information delivery, resource access, and interaction based on the internet. Users access web pages through a browser, the browser requests resources from a server, the server returns content like HTML, CSS, JavaScript, images, and audio/video, and the browser then parses and renders these resources into the pages we see.
The web frontend system actually revolves around these 6 core links:
- Resource Location: Finding resources via URLs
- Network Communication: Transmitting resources via HTTP/HTTPS
- Content Description: Describing structure via HTML
- Styling and Presentation: Controlling appearance via CSS
- Behavior and Interaction: Implementing logic via JavaScript
- Browser Rendering: Turning code into a visible and operable interface for users
Frontend development is about building 'the part of the system that users can see and directly interact with.'
2. What Makes Up a Web Page?
A most basic web page typically consists of three parts:
- HTML: Responsible for structure. What is on the page.
- CSS: Responsible for presentation. How the page looks.
- JavaScript: Responsible for behavior. What happens on the page.
A simple analogy can help understand:
- HTML is like the steel frame and wall structure of a house
- CSS is like the decoration, lighting, colors, and layout of the house
- JavaScript is like the house's electrical system, access control, buttons, and automation
These three together form the frontend page.
3. What is a Browser?
A browser is not simply 'software for searching web pages.' It is essentially a complex runtime environment, undertaking at least these responsibilities:
- Initiating network requests
- Parsing HTML / CSS / JavaScript
- Building the DOM tree and CSSOM tree
- Generating the render tree and completing layout and painting
- Executing JavaScript code
- Maintaining mechanisms like the event loop, timers, and network callbacks
- Providing numerous Web APIs, such as
localStorage,fetch,history,canvas
Common browsers include:
- Chrome
- Edge
- Firefox
- Safari
- Opera
4. What is a Browser Engine?
The browser engine typically refers to the rendering engine and JS engine related parts. When mentioned in frontend development, it's more about how it parses pages and executes code.
Common engines include:
- Blink: Used by mainstream Chromium-based browsers like Chrome, Edge, Opera
- WebKit: Used by Safari
- Gecko: Used by Firefox
- Trident: Used by older versions of IE
Historically, many 'compatibility issues' essentially stemmed from different browser engines having varying levels of support for standards.
5. Why Are Web Standards Necessary?
Without unified standards, different browsers would implement things in their own ways. A page you write might work fine in Chrome, be distorted in Firefox, and have issues in Safari.
That's why standards organizations like W3C and WHATWG are needed to drive the development of standards for HTML, CSS, DOM, URL, Fetch, etc.
The significance of Web standards is very practical:
- Reducing compatibility costs
- Making web pages easier to maintain
- Enabling access from different devices
- Making pages more understandable for search engines
- Providing common rules for engineering collaboration
In today's frontend development, standards awareness is very important. Because many questions aren't about 'can this run,' but rather 'is this correct, stable, and maintainable.'
II. Frontend Development Environment and Basic Tools
1. What Do You Need at Minimum?
For getting started in frontend, the first set of basic tools is usually:
- A computer
- A browser (Chrome is recommended)
- A code editor (VS Code is recommended)
- A local static server or development tool
If you're just learning HTML and CSS, a browser and an editor might even be enough. But once you get into JavaScript modularization, npm, build tools, and framework development, you'll need a Node.js environment.
2. Why is the Editor Important?
Frontend projects have many files and complex structures; an editor is not just a 'notepad for writing code.' A good editor directly impacts efficiency.
Common advantages of VS Code:
- Rich plugin ecosystem
- Convenient Git integration
- Strong debugging capabilities
- Very complete support for the frontend ecosystem
- Practically the de facto standard for team collaboration
Common plugin categories include:
- Code formatting
- Syntax highlighting
- Path hinting
- ESLint / Stylelint
- Git change indicators
- Browser auto-refresh
3. Learn Browser Developer Tools Early
Many beginners write pages by only following the cycle: 'change code -> refresh page -> see result.' This is slow and inefficient.
Browser DevTools are a must-use tool for frontend developers. At least be familiar with:
- Elements: Inspect and debug DOM / CSS
- Console: Run JS, view errors, print logs
- Network: View requests, status codes, response times, caching status
- Sources: Debug JavaScript with breakpoints
- Application: View cookies, storage, cache
- Performance: Analyze performance bottlenecks
To advance in frontend skills, debugging ability is very important.
III. HTML: The Foundation of Page Structure
1. What is HTML?
HTML stands for HyperText Markup Language. It is not a programming language, but a markup language used to describe document structure.
'HyperText' has two meanings:
- It's not just text; it can also carry content like images, audio/video, and forms
- It can link from one page to another via hyperlinks
The core task of HTML is to describe 'what is on the page.'
2. The Most Basic Structure of an HTML Page
A modern HTML page typically looks like this:
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>一只喵博客</title>
</head>
<body>
页面内容
</body>
</html>Here are a few key points:
<!doctype html>: Tells the browser to parse in HTML5 standards mode<html>: The root element<head>: Contains meta-information, not directly displayed content<body>: The main body of the page, where most content users see resides<meta charset="UTF-8">: Specifies character encoding to prevent garbled text<meta name="viewport">: Basic configuration for mobile adaptation
3. HTML Tags and Elements
An HTML page is composed of various tags, which are divided into:
- Paired tags: Have a start and an end, like
<p></p> - Self-closing tags: Close themselves, like
<img>,,<input>
Tags, combined with content and attributes, form elements.
For example:
<a href="/about" target="_blank">关于一只喵博客</a>Here:
ais the tag namehref,targetare attributesAbout Usis the content- The whole thing is a hyperlink element
4. Semantic HTML
Many beginners like to fill the screen with div. The page might run, but this isn't called writing well.
Semantic HTML means using the correct tags to express the correct content structure.
For example:
- Use
h1~h6 - for headings
p - for paragraphs
nav - for navigation
article - for article bodies
main - for the main page content
header,footer - for headers and footers
ul/ol - for lists
button
as the preferred choice for buttons
- The benefits of semantic HTML are many:
- Clearer structure
- Easier to maintain
- Better for SEO
- Better for accessibility
More friendly for subsequent team collaborationA simple principle when writing frontend structure is: first think about the meaning the tag expresses, then write the styles.
5. Common Tag Overview
Headings and Paragraphs
<h1>主标题</h1>
<p>这是一个段落。</p>h1 is usually used for the most important main title of the page. A page isn't strictly forced to have only one h1, but from a content organization perspective, its use should be restrained.
Links and Images
<a href="https://example.com">访问一只喵博客</a>
<img src="avatar.jpg" alt="易喵的头像"/>The alt attribute for images is very important; it serves as alternative text when the image fails to load and is also related to accessibility and SEO.
Lists
<ul>
<li>HTML</li>
<li>CSS</li>
<li>JavaScript</li>
</ul>Navigation, menus, news lists, and comment lists are all very suitable for representation using list tags.
Container Tags
<div></div>
<span></span>They have no semantics themselves and are just generic containers.div is often used for block-level layout, span is often used for wrapping inline text.
Tables
Tables are suitable for displaying data, not for page layout.
<table>
<caption>一只喵博客前端学习名单</caption>
<thead>
<tr>
<th>姓名</th>
<th>分数</th>
</tr>
</thead>
<tbody>
<tr>
<td>张三</td>
<td>95</td>
</tr>
</tbody>
</table>Forms
Forms are an important entry point for user interaction with the page.
<form action="/login" method="post">
<label for="username">用户名</label>
<input id="username" name="username" type="text" placeholder="请输入一只喵博客账号"/>
<label for="password">密码</label>
<input id="password" name="password" type="password"/>
<button type="submit">登录</button>
</form>In actual development, forms are a major topic and will be expanded upon later.
6. HTML Paths and Resource Referencing
There are two common ways to write resource paths:
- Relative paths
- Absolute paths
For example:
<img src="./images/logo.png" alt="logo"/>
<img src="../assets/banner.jpg" alt="banner"/>Relative paths find resources based on the file's location within the frontend project, which is the most common and most suitable for local development.
7. Comments, Character Entities, and Basic Conventions
HTML comments:
<!-- 这是注释 -->Common character entities:
<represents<>represents> represents a space&represents&
Basic conventions include:
- Use lowercase for tag and attribute names as much as possible
- Use reasonable indentation
- Quote attribute values
- Keep the structure clear
- Don't overuse non-semantic tags
IV. CSS: Why Pages Can Look Good
1. What is CSS?
CSS stands for Cascading Style Sheets. It controls the stylistic presentation of a page, such as:
- Fonts
- Colors
- Spacing
- Borders
- Layout
- Animations
- Responsive adaptation
If HTML is responsible for 'what is on the page,' then CSS is responsible for 'how the page looks.'
2. Three Ways to Include CSS
Inline styles
<p style="color: red;">你好,一只喵博客</p>Internal styles
<style>
p {
color: red;
}
</style>External styles
<link rel="stylesheet" href="style.css"/>In actual development, external styles are almost always recommended for reusability and maintainability.
3. Selectors
The core of CSS is 'selecting an element and giving it styles.'
Common selectors include:
/* 一只喵博客:标签选择器 */
p {}
/* 类选择器 */
.card {}
/* ID 选择器 */
#app {}
/* 后代选择器 */
.nav a {}
/* 子选择器 */
.list > li {}
/* 伪类 */
a:hover {}
/* 属性选择器 */
input[type="text"] {}Writing CSS isn't about making selectors more complex; it's about making them clearer and more maintainable.
4. Specificity
When different styles apply to the same element, the browser needs to decide which rule to ultimately use. This involves specificity.
Rough order:
!important- Inline styles
- ID selectors
- Class / attribute / pseudo-class
- Tag / pseudo-element
- Universal selector / inheritance / default styles
But in actual development, it's not recommended to solve problems by frantically stacking specificity. It's better to:
- Control selector complexity
- Standardize naming
- Keep style organization hierarchical
- Use
!important
sparingly
5. The Box Model
- In CSS, almost every element can be understood as a box. The box model consists of four parts:
- content: The content area
- padding: The inner spacing
- border: The border
margin: The outer spacingIn the standard box model, width
.box {
width: 200px;
padding: 20px;
border: 10px solid #333;
margin: 16px;
/* 示例盒子 */
}only accounts for the content area width.If it's the standard box model, total width = 200 + 202 + 10
2 + 16*2.box-sizing: border-box; makes width include padding and border, which is very commonly used in modern development.
* {
box-sizing: border-box;
}6. display and Element Types
Common display types:
block: Block-level element, occupies its own lineinline: Inline element, cannot directly set width and heightinline-block: Can display inline but also set width and heightnone: Not displayed, and removed from the document flowflex: Flexible layout containergrid: Grid layout container
div is block by default, span is inline by default.
7. position Positioning
Positioning is one of the foundations of frontend layout.
static
Default value, laid out according to normal document flow.
relative
Relative positioning, offset relative to its original position; the original space is still preserved.
absolute
Absolute positioning, positioned relative to the nearest positioned ancestor element; if none exists, relative to the viewport or initial containing block.
fixed
Fixed positioning, positioned relative to the browser window; does not move when the page is scrolled.
sticky
Sticky positioning, behaves like a normal element before a certain scroll threshold, then sticks like fixed after the threshold.
8. Floats and Clearing Floats
Floats were once an important way to create layouts, but are now mainly used for scenarios like text wrapping around images. Since floats are removed from the normal document flow, the parent element is prone to height collapse, so clearing floats is often necessary.
Common clearing methods:
.clearfix::after {
content: "";
display: block;
clear: both;
}Although Flex and Grid have largely replaced float-based layouts, understanding floats is still helpful for reading older projects and understanding document flow.
9. What is BFC?
BFC, Block Formatting Context. You can think of it as an independent layout environment where the layout of internal elements doesn't easily affect the outside.
Common triggering methods:
- Root element
floatnotnoneposition: absolute/fixedoverflownotvisibledisplay: inline-block/table-cell/flex/grid
Common uses of BFC:
- Clearing floats
- Preventing margin collapsing
- Avoiding text wrapping around floated elements
10. Flex Layout
Flex is a layout method that modern frontend developers must master.
.container {
display: flex;
justify-content: center;
align-items: center;
/* 居中布局示例 */
}Common container properties:
flex-directionjustify-contentalign-itemsflex-wrapalign-content
Common item properties:
flexorderalign-self
Flex is very suitable for:
- Horizontal/vertical centering
- One-dimensional arrangement layouts
- Navigation, button groups, card rows
- Left-right structures
11. Grid Layout
If Flex is better at one-dimensional layouts, then Grid is more suitable for two-dimensional layouts.
.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 16px;
}Grid is very useful in admin panels, waterfall-like rule-based layouts, and complex area arrangements.
12. Responsive Layout
Frontend pages are not only displayed on computers. Phones, tablets, desktop devices, landscape/portrait modes, and different resolutions all require the page to have adaptive capabilities.
Common responsive layout techniques:
- Percentages
remvw/vh- Media queries
@media - Flex / Grid adaptive layouts
- Flexible scaling of images and containers
For example:
@media (max-width: 768px) {
.sidebar {
display: none;
}
}13. Reflow and Repaint
These are very high-frequency concepts in frontend performance.
Reflow
When an element's geometric properties change, the browser needs to recalculate the layout.
For example:
- Changing width/height
- Changing position
- Adding/removing DOM elements
- Changing font size
- Changing window size
Repaint
When an element's appearance changes but doesn't affect layout, only a repaint is needed.
For example:
- Changing color
- Changing background
- Changing visibility
The conclusion is:
- Reflow will definitely trigger a repaint
- Repaint does not necessarily trigger a reflow
- Reflow is generally more costly
Optimization directions include:
- Batching style modifications
- Reducing frequent reading/writing of layout properties
- Using
transform/opacityfor animations - Moderately using compositing layers and GPU acceleration
14. CSS Animations and Transitions
Two common methods:
transition
Suitable for simple state-switching animations.
.button {
transition: transform 0.3s ease;
}
.button:hover {
transform: translateY(-2px);
}animation + keyframes
Suitable for more complex, continuous animations.
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}Frontend animations aren't better just because there are more of them; they should be restrained. Good motion effects enhance feedback, not steal attention from the content.
V. JavaScript: Making the Page Truly 'Come Alive'
1. What is JavaScript?
JavaScript is the core programming language of the web frontend. It was originally designed to add interactivity to web pages. Evolving to today, JavaScript is not only a browser scripting language but also an important foundation for Node.js server-side, engineering tools, desktop applications, and mobile cross-platform solutions.
In the frontend, JavaScript is responsible for:
- Manipulating the DOM
- Responding to events
- Sending network requests
- Processing data
- Controlling page state
- Driving components and framework operation
2. Primitive Data Types and Reference Types
Common primitive types in JavaScript include:
numberstringbooleanundefinednullsymbolbigint
Reference types are mainly objects:
ObjectArrayFunctionDateRegExp- Other structures built on objects
Understanding the difference between "value types" and "reference types" is crucial for variable assignment, parameter passing, copying, and comparison.
3. Data Type Detection
There are three common methods.
typeof
typeof 1; // 'number'
typeof 'abc'; // 'string'
typeof true; // 'boolean'
typeof undefined; // 'undefined'
typeof function(){}; // 'function'
typeof null; // 'object'The advantage is simplicity; the disadvantage is insufficient granularity for distinguishing null, arrays, and objects.
instanceof
[] instanceof Array; // true
{} instanceof Object; // trueSuitable for determining reference type instances, but not very effective for literal primitive types.
Object.prototype.toString.call
Object.prototype.toString.call([]); // [object Array]
Object.prototype.toString.call(null); // [object Null]This is a more reliable, fine-grained determination method.
4. Variable Declarations: var, let, const
var
- Function scope
- Has variable hoisting
- Can be redeclared
- Global
varattaches towindow
let
- Block scope
- Has a temporal dead zone
- Cannot be redeclared
- More suitable for declaring variables that will change
const
- Block scope
- Must be initialized upon declaration
- Cannot be reassigned
- More suitable for constant bindings
In modern development, the general recommendation is:
- Default to
const - first, use
let - when reassignment is needed, and try to avoid
var
5. Scope and Scope Chain
Scope determines the accessibility of variables and functions.
Common scopes:
- Global scope
- Function scope
- Block scope
When a variable cannot be found in the current scope, JavaScript looks upwards along the lexical scope until the global scope. This lookup path is the scope chain.
This mechanism is fundamental to understanding closures, this, modularization, and execution context.
6. Closures
A closure is not an isolated concept but a natural result of JavaScript's lexical scoping during actual execution.
Simple understanding:A function can remember and access variables in the scope where it was defined, even after the outer function has finished executing.
function outer() {
let articleCount = 0;
return function inner() {
articleCount++;
return articleCount;
};
}
const nextArticle = outer();
nextArticle(); // 1
nextArticle(); // 2Value of closures:
- Preserving state
- Implementing private variables
- Extending the lifecycle of local variables
- Foundation for certain module encapsulation patterns
Risks of closures:
- Improper use can easily lead to increased memory usage
- Readability decreases when logic layers become complex
7. The this Binding
this is one of the most confusing points in JavaScript. It is not bound at definition time, but is determined at call time, with arrow functions being the exception.
Common scenarios:
- Regular function call: points to
windowin non-strict mode, andundefined - in strict mode. Object method call: points to the object calling it. Constructor call: points to the newly created instance. Explicit binding via
- Constructor call: points to the newly created instance
call/apply/bind: points to the specified object. Arrow function: does not have its own- Arrow function: does not have its own
this, inheritsthis
from the outer lexical environment. To understand this, don't memorize rules; the key is to see how the function is called.
8. Prototypes and the Prototype Chain
JavaScript does not use traditional class-based inheritance but is prototype-based.
Every function object has a prototype, and every object has an internal prototype link to its constructor's prototype object. When looking up a property, if the object itself does not have it, the search continues up the prototype chain.
This is the prototype chain.
Understanding the prototype chain helps understand:
- Why instances can access methods on the constructor's prototype
The judgment logic ofinstanceof- The underlying nature of classes and inheritance in JS
9. What new Does
The new
- keyword roughly does the following: Creates a new object. Points the new object's prototype to the constructor's
- prototype
. Executes the constructor with the new object as - this
. If the constructor explicitly returns an object, returns that object; otherwise, returns the new object.If the constructor explicitly returns an object, returns that object; otherwise, returns the new object. - If the constructor explicitly returns an object, returns that object; otherwise, returns the new object.
Therefore, new is not just "syntactic decoration" but part of the object instantiation mechanism.
10. Arrays, Objects, and Common Methods
In frontend development, data processing is almost inseparable from arrays and objects.
Common array methods:
push/popshift/unshiftmapfilterreducefindsome/everyforEachsortslice/splice
Common object operations:
- Property reading and modification
Object.keysObject.valuesObject.entriesObject.assign- Spread operator
... - Deep copy and shallow copy issues
Although these are fundamental, they are used almost every day.
11. DOM and BOM
In the browser, JavaScript is not just the language itself; it can also manipulate the page and environment through APIs provided by the browser.
DOM
Document Object Model, used to represent the HTML document structure.
Common operations:
- Finding elements
- Modifying text and attributes
- Modifying styles
- Adding/removing nodes
- Event listening
BOM
Browser Object Model, representing the browser window environment.
Common objects:
windowlocationhistorynavigatorscreenlocalStorage
12. Event Mechanism
Frontend interaction heavily relies on events, such as clicks, input, scrolling, submission, and keyboard operations.
The event flow generally includes three phases:
- Capture phase
- Target phase
- Bubbling phase
Common methods:
element.addEventListener('click', handler);Common properties and methods in the event object:
targetcurrentTargetpreventDefault()stopPropagation()
Understanding event propagation helps with delegation, component interaction, and performance optimization.
13. Throttling and Debouncing
These two often appear in high-frequency event optimization.
Debouncing
Executes only the last call after a period of inactivity following the trigger.
Suitable for:
- Search input
- Form validation
- Post-resize processing
Throttling
Executes at most once within a specified time period.
Suitable for:
- Scroll listening
- Mouse movement
- High-frequency click control
Essentially, both control the frequency of function calls, differing in their trigger strategies.
Six, Asynchrony, Promise, Event Loop: The Most Common Stumbling Block in Frontend
1. Why Asynchrony Exists
JavaScript executes on the browser's main thread. If all tasks were executed synchronously and blocking, the page would easily freeze.
For example:
- Network requests need to wait for server responses
- Timers need to trigger at a future time
- User clicks and input are unpredictable
- File reading and animation frame callbacks also cannot block the main thread synchronously while waiting
Therefore, the JavaScript runtime needs a mechanism to coordinate synchronous code and asynchronous tasks; this is the purpose of the event loop.
2. Synchronous vs. Asynchronous
Synchronous
Code executes line by line in order; the next line cannot start before the previous one finishes.
Asynchronous
After initiating a task, it does not block the current execution flow. Once conditions are met, the callback is placed into a pending execution queue.
3. Macrotasks and Microtasks
This is key to understanding the event loop.
Common macrotasks:
setTimeoutsetIntervalscript- I/O callbacks
- UI events
Common microtasks:
Promise.then/catch/finallyqueueMicrotaskMutationObserver
The execution order can be summarized as:
- Execute the current synchronous code
- Empty the current microtask queue
- Take one macrotask to execute
- Empty the microtask queue again
- Continue looping
Therefore, usually Promise.then executes earlier than setTimeout.
4. Promise
Promise is one of the standard solutions for handling asynchrony in JavaScript. It represents the future result of an asynchronous operation.
A Promise has three states:
pendingfulfilledrejected
Once the state changes from pending to fulfilled or rejected, it will not change again.
Common methods:
thencatchfinallyPromise.allPromise.racePromise.allSettledPromise.any
The emergence of Promise solved the problem of deeply nested callbacks, allowing asynchronous flows to be organized in chains.
5. async / await
async/await is syntactic sugar built on top of Promises. It does not make asynchrony synchronous, but rather makes asynchronous code look more like a synchronous flow.
async function getData() {
const blogUser = await fetchUser();
const articles = await fetchPosts(blogUser.id);
return { blogUser, articles };
}It makes code more readable and is more suitable for writing serial asynchronous logic.
Points to note:
awaitis usually followed by a PromiseAnasyncfunction returns a Promise.awaitpauses the subsequent execution of the currentasync- function but does not block the entire thread. Error handling should be paired with
try/catch
6. Differences between Timers, Promise, and async/await
setTimeoutis a macrotask scheduling provided by the browser.Promise.thenis a microtask. The underlying implementation ofasync/awaitis still based on Promises. Understanding the execution order among these three is almost a high-frequency interview question for frontend positions.
Understanding the execution order among these three is almost a high-frequency interview question for frontend positions.
Seven, HTTP, HTTPS, and Network Basics: Why Pages Can Request Data
1. What is HTTP
HTTP is the Hypertext Transfer Protocol, used to transfer resources between clients and servers.
Initially mainly used for transferring web pages, it now also handles the transfer of API data, images, audio, video, and other resources.
HTTP itself is a stateless protocol, meaning the server does not remember the business context between two requests by default. Mechanisms like Cookies, Sessions, and Tokens are needed to assist with state management.
2. What is HTTPS
HTTPS can be understood as "HTTP + TLS/SSL encryption layer".
On top of HTTP, it adds:
- Data encryption
- Identity authentication
- Integrity verification
The significance of HTTPS is not just "more secure"; it is a default requirement for modern web infrastructure. Without HTTPS, many modern browser capabilities are restricted, such as certain geolocation, camera, and Service Worker features.
3. Differences between HTTP and HTTPS
Core differences:
- HTTP transmits in plain text; HTTPS transmits encrypted
- HTTP default port 80; HTTPS default port 443
- HTTPS requires a certificate
- HTTPS handshake cost is higher, but in modern network environments, this extra overhead is mostly worthwhile
4. The General HTTPS Process
Simplified understanding:
- Client initiates an HTTPS request
- Server returns a digital certificate
- Client verifies the certificate's validity
- Both parties negotiate encryption algorithms and session keys
- Subsequent communication uses the session key for encrypted communication
Modern TLS is far more complex than this process, but mastering this main line is sufficient at the introductory stage.
5. URL, Request, and Response
A URL typically contains:
- Protocol:
https:// - Domain:
yizhimiao.blog - Port:
:443 - Path:
/api/user - Query parameters:
?id=1 - Hash:
#section1
When the browser sends a request, it includes a request line, request headers, and a request body; when the server responds, it returns a status line, response headers, and a response body.
6. Common HTTP Methods
GET: Retrieve a resourcePOST: Submit dataPUT: Full updatePATCH: Partial updateDELETE: Delete a resourceOPTIONS: Check methods supported by the server, common in CORS preflight
7. Common Status Codes
2xx Success
200 OK201 Created204 No Content
3xx Redirection
301 Moved Permanently302 Found304 Not Modified
4xx Client Error
400 Bad Request401 Unauthorized403 Forbidden404 Not Found
5xx Server Error
500 Internal Server Error502 Bad Gateway503 Service Unavailable
Status codes are not meant for rote memorization but are important clues for troubleshooting request issues.
8. Caching: Why Sometimes Requests Are Not Actually Sent
Browser caching is divided into two main categories:
Strong Cache
The browser uses the local cache directly without sending a request.
Controlled by these fields:
Cache-ControlExpires
Negotiated Cache
The browser sends a cache identifier to ask the server: "Can I still use this resource?"
Controlled by these fields:
ETag/If-None-MatchLast-Modified/If-Modified-Since
If the resource hasn't changed, the server returns 304, and the browser continues to use the cache.
The caching mechanism is an important cornerstone of frontend performance optimization.
9. Cookie, localStorage, sessionStorage
These are often asked about together.
Cookie
- Automatically included in request headers
- Small capacity
- Expiration time can be set
- Commonly used for login state and server-side identification
localStorage
- Stored locally in the browser
- Persists long-term unless actively cleared
- Not automatically sent to the server
- Suitable for persistently storing some frontend data
sessionStorage
- Only valid for the current session window
- Cleared when the window is closed
- Not automatically sent to the server
Their differences essentially lie in:Storage location, lifecycle, and whether they automatically participate in requests.
10. What is Cross-Origin
Browsers enforce a same-origin policy. Same-origin means:
- Same protocol
- Same domain
- Same port
If any one differs, it may constitute a cross-origin situation.
Cross-origin does not mean "the request cannot be sent out," but rather the browser restricts the frontend script from reading the response result.
11. Common Cross-Origin Solutions
CORS
The most mainstream solution, where the server tells the browser which cross-origin requests are allowed via response headers.
Proxy
Common frontend proxies in development environments, such as Vite / Webpack Dev Server / Nginx forwarding.
JSONP
An older solution, only supports GET, rarely the first choice in modern projects.
postMessage
Suitable for communication between windows and iframe communication.
Eight, TCP, UDP, and From URL Input to Page Display
1. TCP and UDP
TCP
- Connection-oriented
- Reliable transmission
- Order guaranteed
- Has acknowledgment and retransmission mechanisms
UDP
- Connectionless
- Fast speed
- Reliability not guaranteed
- Order not guaranteed
Common web requests in frontend are mainly based on HTTP/HTTPS over TCP.
2. TCP Three-Way Handshake
The general process of establishing a connection:
- Client sends SYN
- Server returns SYN + ACK
- Client sends ACK back
The purpose is to allow both parties to confirm each other's sending and receiving capabilities are normal.
3. TCP Four-Way Wavehand
When releasing a connection, both parties need to confirm the end of sending separately, thus typically undergoing a four-way wavehand.
This process is not something directly manipulated in daily frontend coding, but understanding it helps comprehend the underlying process of network connection establishment and closure.
4. How TCP Ensures Reliable Transmission
Mainly relies on these mechanisms:
- Segmentation and numbering
- ACK acknowledgment
- Timeout retransmission
- Checksum
- Sliding window
- Flow control
- Congestion control
5. From URL Input to Page Load Completion
This is one of the most classic questions, ideal for connecting frontend knowledge systems.
A simplified process can be understood as follows:
- Enter the URL in the browser address bar
- Browser checks the cache
- Performs DNS resolution to obtain the IP address
- Establishes a TCP connection with the server
- If HTTPS, a TLS handshake is also performed
- Browser sends an HTTP request
- Server returns the response content
- Browser parses HTML
- Downloads CSS and parses it into CSSOM upon encountering it
- Downloads and executes JS upon encountering it (may block parsing)
- Constructs the DOM tree
- Combines DOM and CSSOM to generate the render tree
- Layout
- Paint
- After the page becomes interactive, continues processing asynchronous resources, event bindings, and API data rendering
What's truly important about this question is not memorizing the sequence, but whether you can connect networking, caching, browser rendering, and script execution.
Nine, Browser Rendering Principles: Why the Page Finally Displays
1. DOM Tree and CSSOM Tree
After the browser gets the HTML, it doesn't directly "draw it as is" but first parses it into a DOM tree.
After parsing CSS files, a CSSOM tree is formed.
Then the browser combines the two to generate the render tree.
2. The Render Tree is Not the DOM Tree
The DOM tree describes the document structure, but not all DOM nodes appear in the render tree.
For example:
Elements with display: nonedo not enter the render tree. Content withinheadelements typically does not participate in rendering.
3. Layout and Paint
Layout
Calculates the geometric position and size of each visible element.
Paint
Draws the pixels of the elements onto the screen.
Modern browsers further perform optimizations like layering and compositing.
4. Why JS Blocks Page Parsing
When the browser parses HTML and encounters a regular <script>, it defaults to pausing HTML parsing, downloading and executing the script first, then continuing with the subsequent document parsing.
The reason is simple: because JS might modify the current DOM structure, the browser must ensure the correctness of the execution order.
Therefore, script loading strategy is very important.
defer
- Asynchronous download
- Executed in order after HTML parsing is complete
- Suitable for most external scripts
async
- Asynchronous download
- Executed immediately upon download completion
- Does not guarantee execution order consistent with HTML parsing
- Suitable for independent scripts, such as analytics code
5. Why Above-the-Fold Performance Matters
Users don't care what framework or state management you use; they only care about one thing: whether the page is fast.
Above-the-fold performance is affected by many factors:
- HTML response speed
- Whether CSS blocks rendering
- Whether JS is too large
- Whether images are too heavy
- Whether font resources block rendering
- Whether caching is used appropriately
- Whether lazy loading and resource splitting are implemented
Frontend optimization is ultimately about enabling users to see content faster and interact sooner.
X. Forms, Validation, and User Input Handling
1. Why Forms Are Important
A real website doesn't just display content; it needs to let users log in, search, leave comments, place orders, upload, filter, and submit.
These interactions fundamentally rely on forms.
2. Common Form Elements
inputtextareaselectoptionbuttonlabelform
3. Common Types of input
textpasswordemailnumberradiocheckboxfilesubmitresetdate
HTML5 brought many more semantic input types to forms, which also benefits native browser validation and mobile keyboard optimization.
4. Why label Is Important
label is not just "writing a text description." It can enlarge the clickable area and enhance accessibility.
<label for="username">用户名</label>
<input id="username" type="text"/>5. Form Submission Methods
Common form submission methods:
GETPOST
GET is generally used for fetching data, with parameters often visible in the URL.
POST is more suitable for submitting data.
Modern frontend development more often intercepts the default form submission via JavaScript and then uses fetch or axios to send asynchronous requests.
6. Frontend Validation and Backend Validation
The significance of frontend validation:
- Improves user experience
- Reduces invalid requests
- Provides users with more immediate feedback
But frontend validationcannot replace backend validation.
Because frontend logic can be completely bypassed, the true security boundary lies on the server side.
XI. Frontend Performance Optimization
1. What Should Performance Optimization Optimize
Frontend performance generally focuses on:
- Whether the page loads quickly
- Whether the above-the-fold content displays quickly
- Whether interactions feel laggy
- Whether animations are smooth
- Whether resources are too large
- Whether there are too many requests
- Whether re-renders are too frequent
2. Common Optimization Directions
Network Layer
- Enable compression (gzip / brotli)
- Use a CDN
- Implement proper caching
- Reduce the number of requests
- Use HTTP/2
Resource Layer
- Image compression
- Image lazy loading
- Code splitting
- Tree Shaking
- On-demand loading
- Remove dead code
Rendering Layer
- Reduce reflows and repaints
- Optimize long list rendering
- Use virtual lists
- Avoid large-scale synchronous DOM operations
- Control animation performance
Code Layer
- Throttling and debouncing
- Reduce redundant calculations
- Cache results appropriately
- Control side effects
- Avoid meaningless re-renders
3. Common Above-the-Fold Optimization Techniques
- SSR / SSG
- Skeleton screens
- Critical CSS inlining
- Image lazy loading
- Deferred loading of non-critical scripts
- Route-level code splitting
- Preloading critical resources
4. Performance Analysis Tools
Don't optimize based on intuition; learn to read the data.
Common tools:
- Chrome Performance
- Lighthouse
- Network panel
- Web Vitals
- Framework Devtools
Optimization is not "I feel this is faster," but "I can prove it is faster."
XII. Browser Storage, Caching, and Offline Capabilities
1. How to Choose Local Storage
If you just need to store a small amount of simple string configuration:
localStoragesessionStorage
If you need more complex frontend database capabilities:
IndexedDB
2. What Is a Service Worker
A Service Worker can be understood as a programmable proxy layer between the browser and the network.
It can do:
- Offline caching
- Request interception
- Resource caching strategies
- Capabilities like push notifications, when combined
Many PWA (Progressive Web App) capabilities depend on it.
Although you may not need to dive deep immediately at the beginner stage, it's essential to know what problems it solves.
XIII. Git and Project Collaboration: Knowing How to Code Doesn't Mean Knowing How to Do Projects
1. Why Frontend Developers Must Know Git
Modern frontend development is almost impossible to separate from team collaboration. Git is the de facto standard for version management.
It's not just about "saving code"; more importantly, it provides:
- Recording change history
- Supporting multi-person collaboration
- Supporting branch-based development
- Supporting code rollback
- Supporting merge and release process management
2. Common Git Commands
git initgit clonegit addgit commitgit statusgit loggit branchgit checkoutgit switchgit mergegit pullgit push
3. Common Branching Models
In common practice, you might see:
main/master: Stable production branchdevelop: Daily development integration branchfeature/*: Feature branchesrelease/*: Release brancheshotfix/*: Emergency fix branches
No matter how well you write code, if you don't understand the collaboration workflow, it's hard to truly leverage your full potential once you join a team.
XIV. Modularization and Engineering
1. Why Modularization Is Needed
When a project is small, one HTML file referencing multiple JS files can work. But as the project grows, you'll encounter:
- Variable pollution
- Dependency chaos
- Code duplication
- Difficulty in maintenance
Modularization is about splitting code into units with clear responsibilities, well-defined boundaries, and reusability.
2. The Evolution of Modularization
Frontend history has gone through:
- The global function era
- IIFE (Immediately Invoked Function Expressions) for scope isolation
- CommonJS
- AMD / CMD
- ES Module
Today's mainstream standard is ES Module.
import { sum } from './utils.js';
export function add() {}3. Why Build Tools Are Needed
Browsers are not naturally efficient at handling large modular projects, so frontend engineering tools are responsible for:
- Module bundling
- Code transformation
- Compatibility handling
- Resource optimization
- Development server
- Hot Module Replacement
- Output minification
4. What Webpack Does
The core idea of Webpack is:Starting from one or more entry points, it bundles all dependencies in the project into resource packages that the browser can run.
Common capabilities:
- Recognizing dependencies like JS, CSS, images, and fonts
- Loaders for transforming different types of resources
- Plugins for extending the build process
- Code splitting
- Minification and optimization
5. Common Optimization Strategies
include/excludeto narrow the processing scope- Use caching appropriately
thread-loaderfor multi-threaded processing of heavy tasksTerserPluginfor minification- Tree Shaking to remove dead code
- Route-based code splitting
- Properly separating third-party dependencies
6. What Is Babel
Babel is essentially a JavaScript compiler. It primarily does one thing:
Transforms new syntax into code that can run in older environments.
Its general workflow:
- Parse: Parse the code into an AST
- Transform: Modify the AST based on plugins
- Generate: Generate new code
The key to understanding Babel is not memorizing the stage names, but knowing that much of modern frontend "syntactic sugar" and "compatibility" isn't directly understood by the browser, but is pre-processed during the build phase.
7. Why Vite Is Becoming Increasingly Popular
Unlike traditional bundling approaches, Vite leverages the browser's native ESM more in the development environment, starting and compiling on demand, resulting in very fast cold start times.
This is why many new projects now prefer Vite over traditional Webpack scaffolding.
XV. Node.js, npm, and the Frontend Ecosystem Foundation
1. Why Frontend Developers Should Learn Node.js
Although frontend code mainly runs in the browser, modern frontend development cannot be separated from Node.js.
Because:
- Build tools run on Node.js
- Package management depends on Node.js
- Local development servers depend on Node.js
- Many script automation tasks depend on Node.js
So, learning Node.js as a frontend developer is not necessarily about writing backend code, but about understanding and utilizing the engineering ecosystem.
2. What Is npm
npm is one of the most mainstream package management tools in the JavaScript world.
Common operations:
- Installing dependencies
- Updating dependencies
- Managing project scripts
- Publishing packages
package.json is an important configuration file for frontend projects, typically containing:
- Project name and version
- Dependency list
- Script commands
- Build configuration entry point
3. Common Contents in package.json
{
"name": "yizhimiao-blog",
"version": "1.0.0",
"scripts": {
"dev": "vite",
"build": "vite build"
}
}Frontend engineering is essentially a bunch of tools strung together through npm scripts to form a workflow.
XVI. Introduction to Vue: A Typical Representative of Data-Driven Views
1. Why Frontend Frameworks Exist
Pure vanilla JavaScript can certainly build pages, but once the page becomes complex, you'll encounter these problems:
- Tedious DOM manipulation
- Difficult state management
- Hard component reuse
- Interaction logic becoming increasingly scattered
- Maintenance costs rising rapidly
Therefore, the core goal of frontend frameworks is:
To organize UI and state more efficiently.
2. The Core Idea of Vue
Vue is a typical practice of the MVVM pattern.
You can understand it as:
- Describing the interface with data
- When data changes, the view updates automatically
- Developers should minimize direct DOM manipulation
This is "data-driven views."
3. Common Capabilities of Vue
- Template syntax
- Conditional rendering
- List rendering
- Event binding
- Two-way binding
- Computed properties
- Watchers
- Componentization
- Lifecycle
- State management
- Route management
4. What Is Componentization
A component is a reusable, composable UI unit with relatively independent responsibilities.
For example:
- Button component
- Input component
- Modal component
- List component
- Page-level component
Componentization is not just "splitting files into smaller pieces," but making the interface structure and logic boundaries clearer.
5. Why the Lifecycle Is Important
The lifecycle is a series of stages a component goes through from creation, mounting, updating, to destruction.
Its importance lies in:
- When to request data
- When the DOM can be accessed
- When to unbind events and clear timers
This is closely related to component side-effect management.
6. computed vs. watch
computed
is more suitable for deriving a value based on existing state, and it has caching.
watch
is more suitable for listening to a state change and then executing additional side-effect logic.
In many cases, if you can use computed, prefer computed, because it is more declarative.
7. Why nextTick Is Frequently Asked About
Vue updates the DOM asynchronously in batches.nextTick's role is to let you execute a callback after the DOM update is complete.
This explains why immediately reading the DOM after modifying data might give you the old value, while placing it inside nextTick can get the updated result.
8. keep-alive, mixin, Vuex
These are common concepts in the Vue ecosystem:
keep-alive: Caches component statemixin: One of the logic reuse solutions, but can introduce naming conflicts and unclear sourcesVuex: Centralized state management (Pinia is also common in Vue 3 projects)
When learning a framework, it's not just about using the API, but understanding what problems it solves.
XVII. Introduction to React: Another Path for Functional UI
1. The Core Idea of React
React is also a component-based framework, but it emphasizes more:
- UI is a mapping of state
- Everything is a component
- Unidirectional data flow
- Describing the interface in a declarative way
React is not "more advanced than Vue"; it just takes a different design path.
2. What Is JSX
JSX allows you to write HTML-like syntax within JavaScript.
It is not real HTML, but is compiled into React.createElement or newer runtime call forms.
3. Function Components vs. Class Components
In React's early days, class components were common. After the introduction of Hooks, function components became mainstream.
Function components have clear advantages:
- More concise
- Better aligned with the idea of composition logic
- More natural organization of state and side effects
- Reduces the mental burden related to
this
4. The Significance of Hooks
Hooks are not just "adding features to function components"; they are an important way for React to organize state logic.
Common Hooks:
useStateuseEffectuseMemouseCallbackuseRefuseContextuseReducer
5. useEffect and Side Effects
Function components themselves should be as pure as possible. Operations unrelated to rendering but that must happen, such as:
- Requesting data
- Subscribing to events
- Manipulating the DOM
- Starting timers
are all side effects, typically handled within useEffect.
6. Why key Is Important
When React performs list diffing, it needs key to stably identify node identities.
A good key should be:
- Unique
- Stable
- Not changing with renders
Don't casually use array indices, especially when the list might have items added, removed, or reordered, as this can lead to incorrect reuse issues.
7. Why setState Sometimes Appears Synchronous and Sometimes Asynchronous
This is a surface-level difference caused by React's update batching mechanism. What you really should understand is:
- React does not guarantee that state updates take effect immediately and synchronously
- State updates are usually batched
- Reading state requires understanding the current render closure and scheduling timing
8. What Is Fiber
Fiber is a new architecture within React for reconciliation and scheduling updates. The core problem it solves is that traditional synchronous recursive updates can easily block the main thread on large pages.
Fiber makes rendering work more interruptible, resumable, and schedulable, thereby improving interaction responsiveness.
You may not need to dive into the source code immediately, but you should know: it is an important foundation for the evolution of React's performance and concurrency capabilities.
XVIII. Frontend Routing, State Management, and SPA Thinking
1. What Is an SPA
SPA, Single Page Application. Its characteristics are:
- After the initial load, the page body is taken over by the frontend
- Page transitions are more about component-level switching rather than full page refreshes
- Routing and state are managed more on the frontend
Common framework projects are almost all SPAs or hybrid modes.
2. Principles of Frontend Routing
There are two common modes for frontend routing:
- Hash routing: Based on
location.hash - History routing: Based on the History API
What frontend routing essentially does is:
Listen for URL changes, then decide which page component to render.
3. Why State Management Emerged
As an application grows, sharing data between components, passing values across levels, and synchronizing page state become increasingly complex.
Thus, we have:
- Vuex / Pinia
- Redux / Zustand / Jotai, etc.
- Context
State management is not mandatory, but when the data flow becomes complex enough, it greatly reduces maintenance costs.
XIX. Frontend Security
1. XSS
Cross-Site Scripting. An attacker injects malicious scripts into a page, which execute when other users browse it.
Common defense strategies:
- Escape user input
- Avoid casually concatenating HTML
- Use
innerHTML - with caution
- Use CSP
Apply strict filtering for rich text
2. CSRF
Cross-Site Request Forgery. Exploits a user's existing login session to induce requests not intended by the user.
- Common defense strategies:
- CSRF Token
- SameSite Cookie
- Secondary confirmation
Verify Referer / Origin
3. Why Frontend Developers Also Need to Understand Security
Many people think security is solely a backend concern, but in reality, the frontend is also part of the attack surface.
- You don't need to become a security expert right away, but you should at least have these awareness points:
- Don't blindly trust user input
- Don't casually execute externally concatenated scripts
- Have boundary awareness for login state management
Be cautious with file uploads, rich text, cross-origin requests, and third-party scripts
XX. Mobile Adaptation and Multi-Device Experience
1. Why Mobile Can't Just Copy PC
Mobile phones have small screens, high pixel density, different interaction methods, and more complex network environments, so a mobile page isn't just a shrunken PC page.
- 2. Common Adaptation Strategies
Flexible layoutrem- vw
- Media queries
- Responsive breakpoints
- Image adaptation
Touch interaction optimization
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>3. The Role of viewport
This is one of the basic configurations for mobile pages, determining the viewport scaling behavior.
- 4. Common Mobile Considerations
- Tap targets shouldn't be too small
- Pay attention to input fields being obscured by the keyboard
- Scroll areas should be clear
- Balance image and font clarity with file size
Pay even more attention to above-the-fold experience in slow network environments
XXI. How to Systematically Learn Frontend
The biggest problem for many beginners is not a lack of effort, but a chaotic learning path.
1. A Relatively Reasonable Learning Sequence
- Phase 1: Basic Structure and Styling
- CSS
- Page Layout
- Box Model, Positioning, Flex, Grid
- Semantic HTML, Forms, Responsive Design
Phase 2: JavaScript Core
- Variables, Types, Scope
- Functions, Objects, Arrays
- Prototype, this, Closures
- DOM, Events
- Asynchronous Programming, Promise, Event Loop
Phase 3: Browser & Network
- HTTP/HTTPS
- Caching
- Cross-Origin
- From URL to Page Rendering
- Reflow & Repaint
- Browser DevTools
Phase 4: Engineering
- Git
- npm
- Node.js Fundamentals
- Modularization
- Babel
- Bundlers
Phase 5: Frameworks
- Deep Dive into Vue or React (Choose One)
- Componentization
- Routing
- State Management
- Project Structure & Conventions
Phase 6: Advanced Skills
- Performance Optimization
- Security Fundamentals
- SSR / SSG
- Testing
- TypeScript
- Design Patterns & Engineering Practices
2. Pitfalls to Avoid in the Beginner Stage
Memorizing Interview Questions Without Understanding the Context
No matter how much you memorize, if you don't understand the connections between them, you'll get confused when the question is rephrased.
Only Coding Along with Videos, Unable to Work Independently
Tutorial projects are just the beginning. Real growth happens when you build the structure yourself, look up information, locate issues, and complete the process independently.
Obsessing Over Frameworks Too Early, Neglecting Fundamentals
Without a solid foundation, frameworks are just API manuals. You'll be lost the moment the scenario changes slightly.
Excessive Chasing of New Trends
One framework is hot today, another library tomorrow. Chasing trends isn't wrong in itself, but without a foundational base, your knowledge becomes increasingly fragmented.
3. What is the Most Important Skill for Learning Frontend?
It's not "memory" or "knowing how to use libraries," but rather these things:
- Breaking down problems
- Being able to locate errors
- Being able to research information and verify it
- Understanding browser and language runtime mechanisms
- Being able to write maintainable code
- Viewing pages from a user experience perspective
Forge Scattered Knowledge into a System
Web frontend technology evolves very rapidly, but its core thread has always been quite clear:
- Use HTML to describe content structure
- Use CSS to control style and presentation
- Use JavaScript to handle logic and interaction
- Turn code into an interface through the browser
- Exchange resources and data with the server via HTTP
- Organize complex projects through engineering practices
- Improve development efficiency and maintainability through frameworks
- Truly deliver a great project through performance optimization, security awareness, and standard practices
The biggest taboo in learning programming is the "blind men and an elephant" approach. What truly sets people apart is building your ownglobal knowledge mind map:
Know where each piece of knowledge sits within the entire system, understand what problem it solves, and know how it connects to upstream and downstream knowledge.
If we compare frontend to a building, then fundamental knowledge is the foundation, frameworks are the mid-level structure, engineering and performance optimization are the load-bearing system, and real project practice is the daily living experience after you move in.
Lay a solid foundation first, then build upwards, so it's less likely to fall apart halfway.