Frontend Developer Technical Interview Reference

HTML Fundamentals

1. Purpose of the DOCTYPE Declaration

HTML operates as a markup language with formal syntax rules. DOCTYPE, short for Document Type, specifies which HTML or XHTML standard the browser should use to render a page. It must appear before the <html> tag, guiding the parser to interpret the document correctly.

<!DOCTYPE html>
<html>
  ...
</html>

Early versions often used stricter declarations:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
  ...
</html>

2. Contrasting HTML, XML, and XHTML

All three are markup languages.

  • HTML4: A presentation-focused language. Its evolution was implementation-driven, leading to a loose and inconsistent syntax.
  • XML (Extensible Markup Language): Primarily designed for storing and transporting structured data. It enforces strict syntax and is extensible. JSON now often takes its role due to being lighter and faster.
  • XHTML (Extensible HyperText Markup Language): An XML-compliant, stricter reformulation of HTML. It aimed to correct HTML's inconsistencies but eventually gave rise to standardized HTML5.
  • HTML5: The current progressive standard for structuring and presenting web content.

XML enforces rules such as a single root element, proper nesting, case sensitivity, quoted attribute values, and closed tags:

<?xml version="1.0" encoding="utf-8"?>
<root>
  <father id='box'>
    <child>小张</child>
    <child>小王</child>
  </father>
</root>

The term "H5 developer" is a colloquial phrase for a modern web engineer; specific responsibilities depend on the project (e.g., mobile sites, desktop apps, or mini-games).

3. Custom Data Attributes (data-*)

HTML allows embedding extra information on elements via data-* attributes, serving as custom properties.

<div id="mydiv" data-message="Hello,world" data-num="123"></div>

These can be manipulated through JavaScript's dataset API:

let mydiv = document.getElementById('mydiv');

console.log(mydiv.dataset.message);

mydiv.dataset.foo = "bar!!!";

With modern frameworks, raw custom attributes are less common. For instance, Vue often passes identifiers directly:

<tr v-for="item in list" :key="item.id">
  <td>张三</td>
  <td>18</td>
  <td>体育好</td>
  <td>
    <button @click="del(item.id)">删除</button>
    <button>编辑</button>
  </td>
</tr>

4. The Value of Semantic HTML

Semantic markup uses appropriate HTML elements to convey structure and meaning, benefiting developers and automated tools alike.

  • Before semantics: Elements like span and div were used generically, achieving functionality but reducing readability for people and programs.
  • After semantics: Tags such as <p>, <article>, <button>, and <header> explicitly describe their purpose. This improves code clarity, aids team maintenance, enhances SEO, and assists screen readers in generating navigable outlines for accessibility.

Semantic design is especially beneficial for content-rich sites (e.g., documentation, blogs).

5. Upgrades in HTML5 vs. HTML4

  • Standardized DOCTYPE: Simplified to <!DOCTYPE html>.
  • New semantic and functional elements: section, video, nav, aside, canvas, footer, header, etc.
  • Enhanced input types: date, email, url, etc.
  • Additional attributes: charset for meta, async for script.
  • Global attributes: contenteditable, draggable, hidden.
  • New APIs: Local storage, geolocation (navigator.geolocation.getCurrentPosition, requires HTTPS for security), Canvas drawing, WebSocket.

6. Common Use Cases for the <meta> Tag

The <meta> tag's behavior is defined by name or http-equiv combined with content.

  • name: Describes document metadata (SEO keywords, viewport).
  • http-equiv: Simulates HTTP response headers (content type, caching).

Frequent declarations:

<meta name="keywords" content="电商,好货,便宜">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<!-- Simplified charset declaration -->
<meta charset="utf-8">

7. Responsive Images with srcset

The srcset attribute on <img> enables responsive image selection based on device pixel ratio (DPR) or viewport width.

For DPR-based switching:

<img srcset="320.png 1x, 640.png 2x, 960.png 3x" />

For fluid widths, use w descriptors and sizes:

<img alt="img元素srcset属性浅析"
  srcset="320.png 320w, 480.png 480w, 640.png 640w"
  sizes="(max-width: 320px) 100vw, (max-width: 360px) 320px, (max-width: 480px) 360px, (max-width: 640px) 480px, 640px"
  src="640.png"
/>

The browser evaluates the device width against sizes media conditions, finds the matching slot, and loads the closest image from srcset. Clear cache when testing, as browsers do not downgrade quality once a higher-resolution image is loaded.

8. Art Direction with the <picture> Element

The <picture> element contains multiple <source> tags and one fallback <img>, allowing different images for different breakpoints or media conditions.

<picture>
  <source srcset="640.png" media="(min-width: 640px)">
  <source srcset="480.png" media="(min-width: 480px)">
  <img src="320.png" alt="">
</picture>

The browser picks the first matching <source>; if none match, it falls back to the <img>.

9. Differences Between defer and async on <script>

These attributes control script loading and execution to improve page performance.

  • Plain <script src="...">: Blocks HTML parsing; the script is fetched and executed immediately.
  • async: The script downloads in parallel with HTML parsing and executes as soon as it is ready, potentially before parsing completes.
  • defer: The script downloads in parallel with HTML parsing but executes only after the entire document has been parsed and before the DOMContentLoaded event.

Both defer and async load asynchronously; defer preserves execution order while async does not. Placing scripts with these attributes in <head> can improve perceived load speed.

<script defer src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.js"></script>
<script async src="https://cdn.bootcdn.net/ajax/libs/element-ui/2.15.0/index.js"></script>

10. Client-Side Storage Mechanisms

  • Cookies
  • localStorage
  • sessionStorage
  • Web SQL (deprecated)
  • IndexedDB

11. Storage Comparison Table

Mechanism Origin / Lifecycle Capacity & Characteristics
Cookies Pre-HTML5; auto-sent per request ~4KB; limited to ~20 per domain; requires wrapper libraries (e.g., js-cookie); can be set with expiration.
localStorage HTML5+; persists until manually cleared ~5MB; straightforward API; shared across same-origin windows.
sessionStorage HTML5+; cleared when the page session ends ~5MB; per-tab/window scope; API surface similar to localStorage.
Web SQL Non‑standard, largely abandoned in favor of IndexedDB Provided a relational SQL interface; still available in some browsers but not maintained.
IndexedDB HTML5+; suitable for complex client-side data needs No‑SQL key‑value store; large capacity (≥250MB, practically unlimited); supports transactional operations; ideal for offline‑capable or data‑intensive web apps.

CSS Fundamentals

1. Selector Specificity and Priority

The specificity hierarchy (high to low): inline styles > ID selectors > class/attribute/pseudo‑class selectors > type/pseudo‑element selectors.

Specificity is computed as a tuple (A, B, C, D):

  • A = 1 if inline style exists, else 0.
  • B = count of ID selectors.
  • C = number of class, attribute, and pseudo‑class selectors.
  • D = number of type and pseudo‑element selectors.

Example A:

div ul li .red { ... }  /* (0,0,1,3) */

Example B:

#mydiv { ... }          /* (0,1,0,0) */

Compare left to right; (0,1,0,0) wins over (0,0,1,3).

2. Techniques for Hiding Elements

Method Takes Space Interactive Notes
opacity: 0 Yes Yes Fully transparent but still interactive
visibility: hidden Yes No Similar to opacity 0 but not clickable
overflow: hidden Yes No Clips overflowing content
display: none No No Removed from document flow
z-index: -9999 Yes No Buried under other positioned elements
transform: scale(0,0) Yes No Rendered as a zero‑size point
left: -9999px Yes Yes Positioned off‑screen but still focusable

3. Distinguishing px, em, and rem

  • px: Absolute unit; fixed pixel size.
  • em: Relative to the parent element's font‑size (or self if explicitly set). Value can cascade and compound.
  • rem: Relative to the root (<html>) font‑size. Preferred for consistent, scalable responsive designs.

A common mobile‑first approach sets the root font size dynamically via JavaScript or CSS media queries:

html {
  font-size: 16px;
}
@media (max-width: 375px) {
  html {
    font-size: 14px;
  }
}

4. Centering Elements Horizontally

Using auto margins:

.centered {
  width: 500px;
  margin: 0 auto;
}

Inline‑block + text‑align:

.wrapper {
  text-align: center;
}
.inner {
  display: inline-block;
  width: 400px;
}

Flex layout:

.container {
  display: flex;
  justify-content: center;
  align-items: center;
}

Absolute positioning + transform:

.parent {
  position: relative;
  height: 500px;
}
.child {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

5. Positioning Schemes in CSS (position)

  • static: Normal document flow; top/left/z-index ignored.
  • relative: Positioned relative to its normal flow position without affecting other elements.
  • absolute: Positioned relative to the nearest positioned (non‑static) ancestor; removed from normal flow.
  • fixed: Positioned relative to the viewport; stays fixed during scrolling.
  • sticky: Behaves like relative until reaching a defined scroll threshold, then becomes fixed within its containing block.

Sticky Example:

.nav {
  position: sticky;
  top: 0;
  background-color: pink;
}

6. Understanding z-index and Stacking Context

z-index controls the stacking order of positioned elements along the z‑axis (layers). It only applies to elements with a position value other than static.

A child’s z-index is constrained by its parent’s stacking context. If a parent has a lower z-index than a sibling container, the parent’s children cannot overlay the sibling’s children, regardless of their own z-index.

7. Clearing Floats

  • Fixed height on the container.
  • A clearing empty element: <div style="clear:both"></div>.
  • overflow: hidden (or auto) on the container.
  • The clearfix micro‑hack:
.clearfix::after {
  content: "";
  display: block;
  height: 0;
  clear: both;
  visibility: hidden;
}
.clearfix {
  zoom: 1; /* IE trigger */
}

Flexbox and Grid have largely superseded float‑based layouts in modern development.

8. Block Formatting Context (BFC)

A BFC is an independent layout region where boxes are laid out vertically according to normal flow, completely isolated from outside elements.

Triggers for BFC:

  • Root <html> element.
  • position: absolute or fixed.
  • float other than none.
  • overflow other than visible.
  • display: inline‑block, table‑cell, flow‑root, etc.

Practical uses:

Preventing margin collapse:

.block {
  overflow: hidden;  /* creates BFC, prevents margin merging */
}

Containing floats:

.container {
  overflow: hidden;  /* clears internal floats */
}

Two‑column adaptive layout:

.sidebar {
  float: left;
  width: 200px;
}
.main {
  overflow: hidden; /* BFC, avoids wrapping under float */
}

9. CSS Sprites (Image Sprites)

A technique combining multiple small images into a single larger sheet (sprite) to reduce HTTP requests. By adjusting background‑position, different portions of the sheet are displayed.

.icon {
  background-image: url('sprite.png');
  background-repeat: no-repeat;
}
.icon-home {
  background-position: 0 0;
  width: 24px;
  height: 24px;
}
.icon-search {
  background-position: -25px 0;
}

While beneficial for minimizing requests, sprites become harder to maintain (any change requires regenerating the whole sheet) and lose the advantage of individual browser caching. HTTP/2 multiplexing and vector icons (SVG, icon fonts) have reduced their necessity.

10. CSS Media Queries

Media queries enable conditionally applying styles based on device characteristics like viewport width, height, or orientation.

.container { width: 600px; }
@media screen and (max-width: 767px) {
  .container { width: 100%; }
}
@media screen and (min-width: 768px) and (max-width: 991px) {
  .container { width: 750px; }
}

A media query evaluates to true when the media type matches and all exprestions are satisfied.

11. Box Model Fundamentals

Every HTML element is rendered as a rectangular box consisting of:

  • content
  • padding
  • border
  • margin

12. Standard vs. Alternative (border‑box) Box Models

  • box‑sizing: content‑box (default): width/height apply only to the content area. Total box width = content + padding + border; margin is outside.
  • box‑sizing: border‑box: width/height include content, padding, and border. The visible box size is exactly the declared dimension, simplifying responsive grid calculations.

13. Pseudo‑classes vs. Pseudo‑elements

  • Pseudo‑class:(:hover, :nth‑child(), :checked) matches elements in a particular state. Has the same specificity weight as a regular class selector.
  • Pseudo‑element:(::before, ::after) creates virtual elements that are not present in the DOM tree. They can be styled but are not attachable to JavaScript events and cannot be directly accessed via JS.

14. Flexbox (display: flex)

Flexbox facilitates one‑dimensional responsive layout, distributing space and aligning items even when sizes are unknown or dynamic.

Key properties:

  • flex‑direction: row (default), column, row‑reverse, column‑reverse.
  • justify‑content: alignment along the main axis (flex‑start, center, space‑between, space‑around, flex‑end).
  • align‑items: alignment along the cross axis (stretch, center, flex‑start, flex‑end, baseline).
  • flex‑wrap: nowrap (default), wrap, wrap‑reverse.
  • align‑content: alignment of multiple lines on the cross axis when there is extra space.

JavaScript Fundamentals

1. Variable Hoisting

During compilation, JavaScript engines move variable and function declarations to the top of their scope. Only declarations are hoisted, initializations remain in place.

console.log(a); // undefined
var a = 1;

// effectively interpreted as:
// var a = undefined;
// console.log(a);
// a = 1;

let and const do not exhibit the same hoisting behavior and exist within the Temporal Dead Zone until their declaration is reached.

2. Argument Passing: By Value vs. By Reference

  • Primitives are passed by value — a copy of the data is sent.
function update(num) {
  num = 10;
}
let count = 1;
update(count);
console.log(count); // 1
  • Objects (including arrays, functions) are passed by sharing — the reference (pointer) is passed. Mutating the object’s properties affects the original, but reassigning the reference inside the function does not.
function mutate(obj) {
  obj.prop = 'changed';
}
let data = { prop: 'original' };
mutate(data);
console.log(data.prop); // 'changed'

function reassign(obj) {
  obj = { prop: 'new' };
}
reassign(data);
console.log(data.prop); // 'changed'

3. Garbage Collection in JavaScript

Memory allocation is automatic; garbage collectors reclaim memory that is no longer reachable.

Memory Lifecycle: allocate → use → release.

Reference‑counting (obsolete): Tracks number of references pointing to an object. Fails when circular references exist (e.g., a.b = b; b.a = a;).

function cycle() {
  let a = {};
  let b = {};
  a.ref = b;
  b.ref = a;
  return 'cycle';
}
// Both a and b become unreachable but reference count never hits zero.

Mark‑and‑Sweep (modern engines): Periodically traverses the object graph starting from roots (global objects). Unreachable objects are labeled and swept away, correctly handling cycles.

4. Scope Chain

Each execution context (function call) maintains a reference to its outer (enclosing) environment. This chain of references continues up to the global scope, allowing inner functions to access variables declared in outer scopes.

let global = 'global';
function outer() {
  let outerVar = 'outer';
  function inner() {
    console.log(outerVar); // 'outer'
    console.log(global);   // 'global'
  }
  inner();
}
outer();

5. Closures

A closure is formed when a function remembers and accesses its lexical scope even when executed outside that scope.

function createCounter() {
  let calls = 0;
  return function () {
    calls += 1;
    console.log(`invoked ${calls} times`);
  };
}
const counter = createCounter();
counter(); // invoked 1 times
counter(); // invoked 2 times

The primary purpose is data privacy — variables inside the closure cannot be accessed from out side, resembling private fields.

function PersonalRecord() {
  let secret = 'hidden';
  this.getSecret = () => secret;
  this.updateSecret = (v) => { secret = v; };
}
const rec = new PersonalRecord();
console.log(rec.getSecret()); // 'hidden'
rec.secret;                  // undefined

6. Implicit Type Coercion (Awareness)

Loose equality (==) and certain contexts trigger automatic type conversion. Prefer strict equality (===) to avoid surprises. For example, "5" == 5 yields true due to coercion, while "5" === 5 is false.

7. Prototype Chain

Every JavaScript object has an internal [[Prototype]] link (accessible via __proto__ or Object.getPrototypeOf). This link points to the constructor’s prototype object, forming a chain. When a property is accessed, the engine traverses this chain until found or until null is reached.

let obj = { name: 'Tom' };
console.log(obj.hasOwnProperty('name')); // true — own property
console.log(obj.hasOwnProperty('toString')); // false — inherited
// obj → Object.prototype → null

8. Inheritance in JavaScript

Prototypal Inheritance:

function Animal(type) {
  this.type = type;
}
Animal.prototype.speak = function() { console.log('Speaking'); };

function Dog(name) {
  this.name = name;
}
Dog.prototype = new Animal('mammal');
Dog.prototype.bark = function() { console.log('Woof'); };

Combination Inheritance (Pseudoclassical): Uses Parent.call(this) for instance properties and Child.prototype = new Parent() for methods.

function Dog(name, breed) {
  Animal.call(this, 'mammal');
  this.breed = breed;
}
Dog.prototype = new Animal();

Parasitic Combination Inheritance: Avoids calling parent constructor twice by using Object.create(Parent.prototype).

Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;

ES6 class Syntax:

class Animal {
  constructor(type) { this.type = type; }
  speak() { console.log('Speaking'); }
}

class Dog extends Animal {
  constructor(name, breed) {
    super('mammal');
    this.name = name;
    this.breed = breed;
  }
  bark() { console.log('Woof'); }
}

9. Determining Whether a Value is an Array

  • Object.prototype.toString.call(value) === '[object Array]'
  • Array.isArray(value) (ES5.1+)

10. The this Binding Rules

  • Default binding: In non‑strict mode, a plain function invocation sets this to the global object (window / global).
function show() { console.log(this); }
show(); // Window (browser)
  • Implicit binding: When a function is called as an object method, this refers to that object.
const obj = {
  val: 42,
  getVal() { console.log(this.val); }
};
obj.getVal(); // 42
  • Explicit binding: Using call, apply, or bind to specify this.
const other = { val: 100 };
const bound = obj.getVal.bind(other);
bound(); // 100
  • new binding: When invoked with new, this points to the newly created instance.
function Greeting(msg) {
  this.message = msg;
}
const instance = new Greeting('hi');
console.log(instance.message); // 'hi'

Arrow functions do not have their own this; they capture it from the enclosing scope.

const obj = {
  value: 10,
  delayed: function() {
    setTimeout(() => {
      console.log(this.value); // 10, arrow inherits from delayed's this
    });
  }
};

11. Static Promise Methods

  • Promise.resolve(value) → resolved promise.
  • Promise.reject(reason) → rejected promise.
  • Promise.all(iterable): Resolves when all promises fulfill, or rejects with the first rejection. Results are collected in an array.
  • Promise.race(iterable): Settles as soon as one promise settles.

12. Macro‑tasks vs. Micro‑tasks and the Event Loop

Example:

console.log(1);

setTimeout(() => console.log(2), 0);

Promise.resolve().then(() => console.log(4));

console.log(3);
// Output: 1, 3, 4, 2
  • Macro‑tasks: script execution, setTimeout, setInterval, I/O.
  • Micro‑tasks: .then()/.catch() handlers, queueMicrotask(), MutationObserver.

The event loop processes one macro‑task, then drains all micro‑tasks, before moving to the next macro‑task.

When await is used inside an async function, everything after the await becomes a micro‑task.

async function fn() {
  console.log('A');
  await Promise.resolve();
  console.log('B'); // micro‑task
}
fn();
console.log('C');
// A, C, B

13. async/await

These keywords provide syntactic sugar over Promises, enabling asynchronous code that resembles synchronous flow.

async function fetchData(url) {
  try {
    let response = await fetch(url);
    let data = await response.json();
    return data;
  } catch (error) {
    console.error(error);
  }
}

14. Advantages over Raw Promises

  • Linear, synchronous‑like readability, avoiding chained .then() pyramids.
  • Native try/catch error handling.
  • Easier debugging with clear call stacks.

15. Shallow vs. Deep Copy

Shallow copy (spread operator, Object.assign):

const original = { name: 'zs', details: { age: 18 } };
const copy = { ...original };
copy.details.age = 20; // affects original

Deep copy (JSON serialization — loses functions, Symbols, undefined, Date objects):

const deepCopy = JSON.parse(JSON.stringify(original));

For robust deep cloning, use structuredClone() (modern) or a recursive traversal.

HTTP Protocol

1. HTTP Methods

  • HTTP/1.0: GET, POST, HEAD.
  • HTTP/1.1 expanded: PUT, DELETE, OPTIONS, TRACE, CONNECT, PATCH.

2. Method Purposes

Method Typical Use
GET Retrieve a resource. Parameters in URL. Safe & idempotent.
POST Submit data to be processed (create). Payload in body. Not idempotent.
HEAD Like GET but returns only headers (e.g., to check for file size before download).
PUT Replace a resource entirely; can be used for creation if URI is specified.
DELETE Remove a resource.
OPTIONS Describe communication options for the target resource (preflight for CORS).
TRACE Echoes received request for diagnostic purposes.
CONNECT Establishes a tunnel to the server via a proxy, typically for SSL/HTTPS.
PATCH Apply partial modifications to a resource.

Parameter transmission: GET/DELETE via URL query; POST/PUT/PATCH via request body.

3. GET vs. POST

  • Visibility: GET parameters are in the URL, POST in body.
  • Security: GET exposes data in browser history/logs; POST hides it, though both need HTTPS for transport encryption.
  • Character limits: GET limited to ASCII and URL length restrictions; POST supports larger binary payloads.
  • Idempotence: GET is idempotent; POST is not (re‑submitting may create duplicates).

4. HTTP Request Structure

POST /api/v1/orders HTTP/1.1
Host: shop.example.com
Content-Type: application/json
Content-Length: 45

{"item":"book","quantity":2}

Components: request line (method + URL + version), headers, empty line, optional body.

5. HTTP Response Structure

HTTP/1.1 201 Created
Content-Type: application/json
Content-Length: 27

{"id":"1234","status":"ok"}

Components: status line, headers, empty line, optional body.

6. Common HTTP Status Codes

2xx Success

  • 200 OK: Request processed successfully.
  • 201 Created: New resource created (often after POST).
  • 204 No Content: Success but response body is empty.
  • 206 Partial Content: Partial GET satisfied (Range requests).

3xx Redirection

  • 301 Moved Permanently: Resource URL has permanently changed; clients should update.
  • 302 Found: Temporary redirect; often used for login flow.
  • 304 Not Modified: Cached resource is still valid (used with conditional headers).
  • 307 Temporary Redirect: Similar to 302 but preserves original method.

4xx Client Errors

  • 400 Bad Request: Malformed request syntax.
  • 401 Unauthorized: Authentication required.
  • 403 Forbidden: Server understands request but refuses it.
  • 404 Not Found: Resource does not exist.
  • 408 Request Timeout: Server timed out waiting.

5xx Server Errors

  • 500 Internal Server Error: Generic server failure.
  • 503 Service Unavailable: Server overloaded or under maintenance.

A 400 often warrants checking front‑end parameter formatting before blaming the backend.

7. Keep‑Alive (HTTP/1.x)

Keeps a TCP connection open for multiple requests/responses, avoiding repeated handshake overhead.

Connection: keep-alive
Keep-Alive: timeout=5, max=100

Reduces latency and resource consumption but may hold server resources longer. Typically limited by timeout and max.

8. Why HTTPS?

Plain HTTP transmits data in cleartext, vulnerable to eavesdropping and tampering. HTTPS encrypts the channel using TLS/SSL.

9. How HTTPS Achieves Security

Encryption approaches:

  • Symmetric (AES, ChaCha20): Single key for encryption/decryption; fast but key distribution is hard.
  • Asymmetric (RSA, ECC): Public/private key pair. Used initially to securely exchange the symmetric session key.
  • Hash (SHA‑256): One‑way, used for integrity checks and digital signatures.

Practical flow:

  1. Asymmetric encryption securely delivers the symmetric key.
  2. Subsequent data transfer uses efficient symmetric encryption.

Digital certificate (X.509): Issued by a Certificate Authority (CA), binding an identity to a public key. The browser verifies the certificate’s chain, expiration, and that the host matches the certificate. Digital signature: The CA signs a hash of the certificate content; the client verifies this signature using the CA’s public key, ensuring the certificate hasn’t been tampered with.

10. HTTP/2 Enhancements

  • Binary framing layer: Encodes messages in binary for more efficient parsing and transport.
  • Header compression (HPACK): Reduces redundant headers, preserving bandwidth.
  • Server push: Servers can proactively send resources (e.g., CSS/JS) before the browser requests them.
  • Multiplexing: Multiple concurrent streams over a single TCP connection, removing the head‑of‑line blocking present in HTTP/1.x (eliminates the 6‑8 parallel connection limit).

11. HTTP Caching Strategy

Strong Caching If the resource is within its freshness lifetime (defined by Expires or Cache‑Control: max‑age), the browser serves it directly from cache without contacting the server. Status appears as 200 (from disk/memory cache).

  • Expires uses absolute time; causes issues with clock skew.
  • Cache‑Control uses relative seconds and is preferred. Values include max‑age, no‑cache (revalidate before use), no‑store (never cache).

Negotiated (Conditional) Caching When strong cache expires, the browser sends a conditional request to the server using If‑Modified‑Since (based on Last‑Modified) or If‑None‑Match (based on ETag).

  • Last‑Modified / If‑Modified‑Since: Timestamp comparison; can miss sub‑second changes.
  • ETag / If‑None‑Match: A unique hash. More accurate. Server responds with 304 Not Modified (use cache) or 200 (send fresh body).

TCP Protocol

1. TCP Overview

Transmission Control Protocol — a connection‑oriented, reliable, byte‑stream transport layer protocol atop IP. HTTP runs on top of it.

2. A Complete HTTP Request Lifecycle

  1. DNS resolution returns the IP for www.baidu.com.
  2. TCP three‑way handshake to establish a connection.
  3. Browser sends HTTP request.
  4. Server replies with HTTP response containing HTML.
  5. Browser parses HTML, then fetches dependent resources (CSS, JS, images) — potentially over additional HTTP requests or the keep‑alive connection.
  6. Browser renders the page.
  7. TCP four‑way teardown closes the connection.

3. DNS Resolution

Converts domain names to IP addresses. Order: browser DNS cache → OS cache → hosts file → recursive query to DNS resolver.

4. Three‑Way Handshake

Ensures both parties are ready to communicate. A third step prevents stale connection attempts from being opened on the server side.

5. Four‑Way Teardown

Both sides close separately to allow any remaining data delivery.

DOM

1. DOM Event Flow

Three phases:

  1. Capturing phase — event travels from document down to the target.
  2. Target phase — event reaches the element that initiated it.
  3. Bubbling phase — event propagates back up to document.

2. Event Delegation

Uses event bubbling to handle events on child elements through a common ancestor.

document.getElementById('list').addEventListener('click', (e) => {
  if (e.target.tagName === 'LI') {
    console.log(e.target.textContent);
  }
});

Reduces the number of event listeners and automatically handles dynamically added children.

Browser Internals

1. CSS Selector Matching Direction

Browsers match selectors from right to left to minimize traversal. For .mod‑nav h3 span, the engine first finds all spans, then checks if they have an h3 ancestor, and finally if there is an ancestor with .mod‑nav. This is far more efficient than the opposite direction.

2. Browser Rendering Pipeline

  1. Parse HTML → DOM tree.
  2. Parse CSS → CSSOM (style rules).
  3. Combine → Render tree (visual nodes).
  4. Layout (reflow) → compute geometry.
  5. Paint → fill pixels.

3. Reflow and Repaint

  • Reflow (Layout): Recalculates positions and geometries. Expensive.
  • Repaint: Redraws pixels without affecting layout. Less expensive.

Reflow always triggers repaint; repaint does not necessarily trigger reflow.

4. Triggers for Reflow DOM additions/removals, style changes affecting geometry, content changes, viewport resize, initial render.

5. Optimization by Browser Browsers batch reflows and repaints into a single cycle. However, accessing layout‑thrashing properties (offsetWidth, clientHeight, getComputedStyle()) forces an immediate flush, nullifying the optimization.

6. Performance Optimization Tips

  • Batch DOM and style changes.
  • Avoid reading layout properties inside loops.
  • Use transform instead of left/top for animations (compositor‑only).
  • Employ DocumentFragment for bulk DOM insertion:
const fragment = document.createDocumentFragment();
items.forEach(item => {
  let li = document.createElement('li');
  li.textContent = item;
  fragment.appendChild(li);
});
container.appendChild(fragment);

7. WebSocket for Real‑Time Communication

Complements the HTTP request‑response model with a full‑duplex, persistent TCP‑based protocol:

const socket = new WebSocket('wss://example.com/chat');
socket.onmessage = (event) => processMessage(event.data);
socket.send(JSON.stringify({ type: 'hello' }));

Previous solutions (short polling, long polling, SSE) had drawbacks in efficiency, server load, or true bidirectionality.

8. Same‑Origin Policy

A browser security mechanism that restricts cross‑origin reads. Two URLs are same‑origin if they share the protocol, domain, and port. Some elements (<img>, <link>, <script>) bypass this restriction for fetch purposes.

9. Cross‑Origin Solutions

  • JSONP: Uses <script> tag to fetch data via callback. Only supports GET.
  • CORS (Cross‑Origin Resource Sharing): Server sets Access‑Control‑Allow‑Origin and related headers.
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', req.headers.origin || '*');
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  res.header('Access-Control-Allow-Headers', 'Content-Type,Authorization');
  next();
});
  • Proxy: During development (webpack‑dev‑server proxy) or production (Nginx reverse proxy), the backend service routes requests on behalf of the client, circumventing browser restrictions.

Frontend Engineering

1. Babel’s Operation

Parses modern JS into an AST, transforms the AST through plugins, then generates compatible ES5 (or target) code.

2. Building a Basic Babel Plugin (Intro)

A plugin exports a function returning an object with a visitor. The visitor operates on AST nodes. For instance, constant folding:

module.exports = function({ types: t }) {
  return {
    visitor: {
      BinaryExpression(path) {
        if (t.isNumericLiteral(path.node.left) && t.isNumericLiteral(path.node.right)) {
          let result;
          switch (path.node.operator) {
            case '+': result = path.node.left.value + path.node.right.value; break;
            case '*': result = path.node.left.value * path.node.right.value; break;
          }
          if (result !== undefined) {
            path.replaceWith(t.numericLiteral(result));
            let parent = path.parentPath;
            if (parent) this.visitor.BinaryExpression.call(this, parent);
          }
        }
      }
    }
  };
};

3. Git Flow Branching Model

  • master — stable production snapshots.
  • develop — integration branch for features.
  • feature/* — off develop; merged back when complete.
  • release/* — off develop; for testing, bug fixes, final polish; merged into master and develop.
  • hotfix/* — off master; urgent fixes merged into both master and develop.

4. git merge vs. git rebase

  • merge creates an explicit merge commit, preserving full history.
  • rebase replays commits onto another branch, yielding a linear history. Prefer merge for shared/public branches and rebase for local cleanup.

5. git reset vs. git revert

  • git reset --hard <commit> rewinds history (dangerous on shared branches, requires force push).
  • git revert <commit> creates a new commit that undoes changes, safe for collaboration.

Vue

1. MVVM Architecture

  • Model: Data layer (API responses, local state).
  • View: Declarative templates.
  • ViewModel: Binds Model and View; tracks changes and syncs both sides.

2. Pros and Cons of MVVM

Pros: Separation of concerns, automatic DOM updates, improved testability. Cons: Difficulty locating bugs across layers; large ViewModel objects may retain memory if not properly managed.

3. Vue Instance Lifecycle

  • beforeCreate: Instance initialized, data/events not yet reactive.
  • created: Reactivity set up, but $el not mounted.
  • beforeMount: Template compiled, DOM about to be patched.
  • mounted: DOM rendered and accessible.
  • beforeUpdate: Data changed, before DOM re‑render.
  • updated: DOM reflects new data.
  • beforeDestroy: Cleanup opportunity (timers, subscriptions).
  • destroyed: Instance fully torn down.

4. Where to Place Asynchronous Calls

Initiate network requests inside created (data available) or mounted (DOM ready). Avoid beforeCreate and beforeMount; componentWillMount is deprecated in React for similar reasons.

5. Component Communication in Vue

  • Parent → Child: Props (:user="userObj").
  • Child → Parent: Custom events ($emit('event', payload)).
  • Sibling / Arbitrary: Global event bus (discouraged in large apps), $parent / $refs, provide/inject, $attrs/$listeners, or Vuex for centralized state.

6. computed vs. watch

  • computed: Derives new data from existing state; automatically caches until reactive dependencies change.
  • watch: Executes side‑effects in response to data changes (API calls, DOM manipulation).

7. Reactivity System (Vue 2 vs. 3)

  • Vue 2 uses Object.defineProperty on each property — cannot detect new property addition or array index changes.
  • Vue 3 uses Proxy, which wraps the entire object, intercepting property access, assignment, and array mutations natively.

The reactivity system follows an Observer pattern: data changes are colllected as dependencies and trigger updates to subscribers (render functions, watchers, computed properties).

8. Role of key in v‑for

key gives each virtual DOM node a stable identity, enabling the diff algorithm to efficiently reuse and reorder existing DOM elements rather than destroying and recreating them. Always use a unique, stable identifier (not index) during list rendering.

9. Routing Parameter Passing (Vue Router)

  • query (appears in URL):
this.$router.push({ path: '/user', query: { id: 12 } });
// Access: this.$route.query.id
  • params (requires named route, does not appear in URL; lost on refresh unless persisted):
this.$router.push({ name: 'UserDetail', params: { id: 12 } });
// Access: this.$route.params.id

10. Vue SEO Approaches

  • SSR (Nuxt) — fully rendered HTML from server.
  • Static site generation (Nuxt generate) — flat HTML.
  • Prerendering (prerender‑spa‑plugin) — for selected routes.
  • PhantomJS headless browser proxy — for crawling bots.

11. Permission Management in Vue

  • Button permissions: Conditionally render via v‑if using permission identifiers from API.
  • Route permissions: Split routes into static and dynamic. After login, fetch user permissions, filter dynamic routes, add them via router.addRoutes, and store in Vuex for menu rendering.

12. Payment Integration

  • Alipay: Post order info to the backend, receive a form HTML string, inject it into DOM, and auto‑submit.
this.alipayHtml = formString;
this.$nextTick(() => this.$refs.formContainer.children[0].submit());
  • WeChat Pay: Backend returns a payment URL; frontend generates a QR code image.

13. Improving Initial Load Time

  • Route lazy loading (const Foo = () => import('./Foo.vue')).
  • Modern image formats (WebP, AVIF) and compression.
  • CDN for static assets.
  • Enable Gzip/Brotli compression on the server.
  • Code splitting and tree shaking.

14. Handling Technical Challenges

Approach problems by breaking down business requirements, researching solutions (e.g., WebSocket, internationalization, permission control), and iterating implementations. Often difficulties arise from unfamiliar business rules rather than pure technical complexity.

15. Project Introduction Template

For a food‑delivery app:

Tech stack: Vue 2 + Vuex + Vue Router + Axios + Webpack + SCSS + Flexbox. Core modules: geolocation, restaurant listings, search & filtering, shopping cart, order workflow, user authentication, address management, payment, ratings.

React (Optional)

1. Current React Lifecycle

Three deprecated lifecycles (componentWillMount, componentWillReceiveProps, componentWillUpdate) are being phased out. Modern lifecycles:

  • Mounting: constructor -> static getDerivedStateFromProps -> render -> componentDidMount.
  • Updating: getDerivedStateFromProps -> shouldComponentUpdate -> render -> getSnapshotBeforeUpdate -> componentDidUpdate.
  • Unmounting: componentWillUnmount.

2. Data Fetching in React

Recommended in componentDidMount. Avoid componentWillMount/UNSAFE_* due to potential double calls in server‑side rendering and React Fiber concurrency.

3. Nature of setState

  • Asynchronous inside React synthetic events and lifecycle hooks for batch updates.
  • Synchronous within native DOM events and setTimeout.

Access updated state via the callback: this.setState({ count: 1 }, () => console.log(this.state)).

4. Cross‑Component Communication in React

  • Parent → Child: props.
  • Child → Parent: callback functions passed via props.
  • Siblings: lift state to common parent.
  • Deep trees: React Context API.
  • Global state: Redux, MobX, or Zustand.

5. React Performance Optimizations

React.memo, PureComponent, useMemo, useCallback, code splitting (React.lazy, Suspense), avoiding unnecessary re‑renders.

6. Logic Reuse Patterns

  • Higher‑Order Components (HOC).
  • Render Props.
  • Custom Hooks (currently the preferred approach).

7. Comparison of Reuse Patterns

  • HOC: Wraps a component; can cause wrapper hell and naming collisions.
  • Render Props: Shares code by a function prop; can lead to nesting.
  • Hooks: Compose behavior inside functional components; fewer indirection levels but come with rules of hooks and closure traps.

8. Redux Data Flow

Unidirectional: View dispatches an ActionStore forwards to ReducerReducer returns new StateStore notifies subscribers → View re‑renders.

9. react‑redux Bindings

  • <Provider store={store}> makes the store available via context.
  • connect(mapStateToProps, mapDispatchToProps)(Component) subscribes to store slices and injects them as props.

10. Redux vs. MobX

  • Redux: single immutable store, explicit updates, excellent devtools/time‑travel debugging.
  • MobX: multiple observable stores, automatic tracking, less boilerplate but harder to trace state mutations.

Choose Redux for complex flows requiring traceability; MobX for rapid prototyping with simpler state.

11. Redux Async Middleware

  • redux‑thunk: Allows action creators to return functions. Simple but can lead to action‑logic coupling.
  • redux‑saga: Uses generator functions to handle side effects declaratively; powerful but adds complexity.
  • redux‑observable: Based on RxJS; very powerful for reactive stream handling but has a steep learning curve.

Tags: html css javascript HTTP tcp

Posted on Wed, 20 May 2026 19:54:04 +0000 by designxperts