Yuan's Blog
EN

HTML, CSS, Frontend Tooling, Frontend Performance Optimization

HTML Series

  1. HTML Semantics

    • HTML semantics refers to using HTML tags that correctly express their intended meaning. This improves SEO, enhances code readability, helps developers better understand page structure, and contributes to building accessible web pages.
  2. Where should the <script> tag be placed in HTML? What about <link>?

    • When parsing HTML, the browser loads content from top to bottom. When it encounters a <script> tag, it pauses HTML parsing, downloads and executes the JavaScript file, then continues parsing the remaining HTML. Most developers recommend placing <script> before the closing </body> tag to allow the page to render faster and avoid JavaScript manipulating HTML elements that haven’t loaded yet. However, placing it at the end may also cause the page to initially have no functionality. Using defer or async is preferred to allow the browser to parse the page while downloading JavaScript.

    • The <link> tag is typically placed inside the <head> section of the HTML file. It is primarily used to link external resources.

  3. How do you include CSS in HTML? What is the priority order?

    • Inline Styles: <p style="font-size: 20px; color: red;">This is a piece of red text.</p>

    • Internal Styles: CSS placed inside a <style> tag within the <head> section.

    • External Stylesheet: CSS stored in a separate .css file and imported using the <link> tag in the HTML file.

     <!DOCTYPE html>
     <html>
       <head>
         <!-- Include styles via the link tag -->
         <link rel="stylesheet" href="styles.css" />
       </head>
       <body>
         <h1>This is a heading</h1>
         <p>This is a paragraph.</p>
       </body>
     </html>
    
    • Priority: Inline Styles > Internal Styles = External Stylesheet
    1. What is the difference between async and defer in <script>?

      • defer: A deferred script waits until the HTML is fully parsed and the DOM is completely constructed before running. If script A depends on script B, you must ensure B executes before A; defer guarantees order and executes scripts sequentially.
      • async: An async script is downloaded in parallel with HTML parsing, but once downloaded, it executes immediately. This means execution order is not guaranteed.

    CSS Series

    1. Explain CSS selector specificity

      • !important > inline styles > id > class = pseudo-class > type selector = pseudo-element > universal selector
    2. What CSS units exist? How should they be used?

      • px is an absolute unit suited for precise layout.
      • em scales based on the parent or its own font-size, which can compound unpredictably in complex structures.
      • rem always refers to the root element’s font-size, avoiding inheritance chain issues. This makes it the mainstream choice for modern RWD and design systems.
      • In real projects, px is often used for precise local control, while rem provides consistent global scaling; excessive use of em in deep hierarchies should be avoided.
    3. CSS Box Model

      • A box consists of content, padding, border, and margin.
      • border-box includes padding and border within width/height calculations.
      • Margin is never included in width/height; it only affects external spacing.
    4. What are pseudo-classes and pseudo-elements?

      • Pseudo-classes: Apply styles based on element states. Examples: :hover, :link, :visited, :disabled, :enabled, :first-child, :last-child

      • Pseudo-elements: Insert virtual elements without adding actual HTML. Examples:

        • ::before, ::after
        • ::marker
        • ::placeholder
        • ::first-letter
    5. Explain the values and behavior of CSS position

      • static: Default document flow; top/bottom/left/right/z-index have no effect.
      • relative: Makes the element a positioning reference for absolutely positioned children; also allows minor position adjustments.
      • absolute: Removed from document flow; positioned relative to the nearest ancestor with positioning.
      • fixed: Positioned relative to the viewport.
      • sticky: Behaves like relative until a threshold is reached, then sticks like fixed; returns to normal when scrolled back.
    6. Methods for horizontal/vertical centering (flex, grid)

      • Layout types:

        • block: vertical stacking, width 100%
        • inline: horizontal but can’t set width/height
        • inline-block: inline flow but supports width/height
      • Common centering techniques:

        • Flex + align-items + justify-content: Most universal and memorable.
        • Flex + margin:auto: Child consumes remaining space and centers.
        • margin-left/right:auto + max-width:fit-content: Inline-based centering without flex.
        • Grid + place-content:center
        • absolute + transform (top:50% + left:50% + transform:translate(-50%, -50%))
        • fixed + inset:0 + margin:auto: For viewport-level centering, used in modals/banners.
        • text-align:center + line-height: Old-school single-line text centering.
    7. Values of CSS display and their differences

      • block: occupies full width; starts on a new line.
      • inline: flows inline, cannot set width/height.
      • inline-block: inline flow + can set width/height.
      • display:none vs visibility:hidden:
        • display:none: element removed from layout
        • visibility:hidden: element invisible but still occupies space
      • StyleX: Compiles atomic CSS at build-time with deterministic specificity, solving style conflicts, priority disorder, CSS bloat, and scaling issues. More type-safe and maintainable than traditional CSS or Tailwind in large projects.

    Frontend Tooling

    1. What is frontend modularization? The core idea is splitting code into small, maintainable, reusable modules and using a unified loading/bundling system to produce browser-ready applications. ES Modules became the standard, but inconsistent browser implementations and reliance on npm packages led to bundlers like webpack, which convert JS/CSS/images into formats browsers understand while adding compatibility, performance optimization, and improved developer experience.

    2. Difference between webpack loader and plugin

      • loader: Processes files so webpack can understand types like CSS, TypeScript, Sass.
      • plugin: Extends webpack’s build process—controls lifecycle hooks, optimizes output, injects variables, auto-generates HTML, etc. Loaders are functions; plugins are objects with apply().
    3. Why is pnpm faster and more space-efficient than npm?

      • pnpm uses a global content-addressable store + hard links + local cache to avoid duplicated dependencies, greatly boosting install speed and reducing disk usage.
    4. Vite

      • A build tool that leverages modern browsers’ native support for ES modules (import/export), eliminating the need for heavy upfront bundling during development.
    5. Why use a monorepo?

      • Easier shared code across multiple projects, unified updates, avoids version inconsistencies.
    6. What is a frontend build tool and why use one?

      • Build tools transform development code (React/Vue/TS/ESNext) into optimized output browsers can run efficiently, while improving DX during development.

    Frontend Performance Optimization

    1. What are Reflow and Repaint, and how to optimize them?

      • Reflow: Browser recalculates layout positions and sizes — highest cost.
      • Repaint: Visual updates (like color) that don’t affect layout — lower cost.
      • Optimization focuses on avoiding layout changes:
        • Use transform instead of layout-affecting properties
        • Use opacity for show/hide
        • Promote frequently changing elements to a separate layer (will-change)
        • Reduce DOM thrashing and unnecessary recalculations
    2. What is debounce? How to implement it?

      • Debounce merges a burst of rapid events into a single execution.
      • Only after the user stops triggering events for a certain delay will the function execute.
      • Common use case: prevent a search box from firing API calls for every keystroke.
function debounce(fn, delay = 300) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), delay);
  };
}

const search = debounce((text) => {
  console.log("Call API:", text);
}, 300);
  1. What is throttle? How do you implement a throttle function?
  • Throttling ensures that a function is executed at most once within a fixed time interval, even if the event is triggered continuously.
  • It is suitable for scenarios like scrolling, dragging, and window resizing—cases where events fire rapidly but should not be handled too frequently.
  • Debounce vs throttle:
    • Debounce executes only after the user stops triggering the event.
    • Throttle executes at a fixed, controlled pace regardless of how often the event fires.
function throttle(fn, delay = 500) {
  let timer = null;
  return (...args) => {
    if (timer) return;
    timer = setTimeout(() => {
      fn(...args);
      timer = null;
    }, delay);
  };
}

const onScroll = throttle(() => {
  console.log("Default");
}, 500);

window.addEventListener("scroll", onScroll);
  1. What is the Critical Rendering Path?
  • The critical rendering path is the entire process where the browser turns HTML/CSS/JS → a visible, interactive page.
  • Performance optimization focuses on making the following steps faster: DOM, CSSOM, JavaScript execution, Layout, and Paint.
  • Main controllable factors:
    • HTML as small as possible → fewer DOM nodes
    • CSS as fast as possible → smaller files, placed early, non-critical CSS loaded asynchronously
    • JavaScript should avoid blocking DOM/CSSOM construction
  • Example: If a homepage tries to render 100,000 list items at once, Layout + Paint may take hundreds of milliseconds; but rendering only the 50 items in the viewport (virtual list) can reduce render time from 242ms → around 2ms.

  1. How to prevent memory leaks in frontend systems?
  • Frontend memory is the RAM used by the browser to store JavaScript variables, objects, event listeners, DOM nodes, etc.
  • If the page keeps references to objects that are no longer needed but still referenced, the garbage collector cannot free them, causing memory leaks.
  • Over time this leads to sluggish performance and even page crashes.

  1. How to use DevTools to locate issues?
  • Elements: Inspect DOM, tweak styles, adjust layout, review the box model, and live-edit CSS. Use this panel when: button styles are incorrect, elements disappear, layout is misaligned.

  • Console: Run JS, check errors, debug variables, print logs. Useful for: front-end logic bugs, checking API responses.

  • Sources: Breakpoints, step-by-step debugging, view original source via Source Maps, analyze execution flow. Use when: logic behaves unexpectedly, a state is undefined, or you need to trace execution.

  • Network: View all HTTP requests, debug APIs, analyze loading performance. Detects: 404 errors, CORS issues, slow requests, large payloads.

  • Performance: Record page performance, find jank, long tasks, reflows/repaints, script bottlenecks. Use for: scroll lag, animation frame drops, overall page slowness.


  1. What is SPA (Single-Page Application)? What are its pros and cons?
  • A SPA uses a single HTML file; all subsequent content updates happen through JavaScript without full page reloads.

Problems & Solutions

  • Poor SEO

    • Solution: SSR (Server-Side Rendering) renders full HTML on the server before sending to the browser.
    • SSR + CSR hybrid flow:
      1. First load = SSR (server renders full HTML)
      2. Client JS loads and hydrates the page
      3. Subsequent navigation & interactions = CSR like a normal SPA
  • JavaScript bundle too large

    • Lazy Loading: load components/routes only when needed
    • Code Splitting: break a large bundle into smaller chunks
    • JS minification
    • Tree Shaking: remove unused code

  1. Frontend image format selection
  • Raster images (pixel-based): JPG / PNG / WebP / GIF
  • Vector images (math-based): SVG

Best practice:

  • Photos → JPG
  • Transparency → PNG
  • Icons → SVG
  • If possible, use WebP for everything
  • Avoid GIF; replace with WebM