Token导航 LogoToken导航

Agent Skill · 研究检索

rendering-patterns(渲染模式)

rendering-patterns 用于查找、检索和筛选相关信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要根据关键词、任务场景或来源线索快速定位候选结果时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

rendering-patterns 是研究检索类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为操作浏览器;许可证信息还不明确,第三方扫描有未通过项,按安装量在研究检索类的 73,675 个 Skill 里排第 69,087。

总安装 220周安装 9GitHub Stars 34下载 71核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
unknown

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:rendering-patterns(渲染模式)
来源仓库:https://github.com/kinfe123/fm-skills
仓库路径:skills/rendering-patterns
安装命令:
npx skills add https://github.com/kinfe123/fm-skills --skill rendering-patterns
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/kinfe123/fm-skills --skill rendering-patterns

这个 Skill 是做什么的

研究检索类 Skill 主要解决「找资料、核对事实、把来源整理清楚」的问题,通常会让助手先检索再总结。

rendering-patterns 用于查找、检索和筛选相关信息,适合在 Codex、Claude、Cursor、Gemini CLI 中根据关键词快速定位候选结果。它支持按仓库、安装命令和原始 README 核验具体用法,适用于信息调研类任务。

通过 npx skills add 命令从指定 GitHub 仓库安装,需确认权限与维护状态。安装前建议检查是否会触发联网、命令执行或文件读写操作。适用宿主包括 Codex、Claude、Cursor、Gemini CLI,接入前应确认版本、权限和运行环境要求。

来源仓库内路径:skills/rendering-patterns

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/kinfe123/fm-skills --skill rendering-patterns;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要操作浏览器,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

rendering-patterns 怎么安装?

在终端执行 npx skills add https://github.com/kinfe123/fm-skills --skill rendering-patterns。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

rendering-patterns 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

rendering-patterns 需要什么权限?

权限级别是操作浏览器。该 Skill 可能涉及浏览器控制能力,使用时可能读取或操作网页内容,需要在受控环境中确认权限边界。

rendering-patterns 是免费的吗?

公开资料没有标注明确许可证,收费和商用限制都无法确认。正式使用前请到来源仓库核对授权说明。

rendering-patterns 用的人多吗?

公开数据是累计安装 220 次,近一周安装 9 次,下载 71 次,GitHub 34 星。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

rendering-patterns 安全吗?

第三方扫描有未通过项,风险较高。除非你确认过源码,否则不建议直接安装到常用环境。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。

先想清楚的地方

  • 许可证没有明确标注,能不能商用、能不能再分发都不确定。
  • 第三方扫描存在提醒项或未通过项,需要人工逐条确认。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理研究检索类任务、又不想每次都手写提示词的人。

不太适合

  • 需要明确授权才能用到公司项目里的场景。
  • 需要厂商级技术支持和 SLA 的生产系统。

研究检索类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
find-skills

寻找技能 · Codex、Claude

31,199,81316,486操作浏览器MIT有提醒
self-improving-agent

自我改进 Agent · OpenClaw

16,464,0023,396接触敏感数据MIT-0通过
soultrace

灵魂追踪 · Codex、Claude

7,588,94412需要联网未明确有提醒
self-improving

自我完善 · OpenClaw

6,829,2841,046需要联网MIT-0通过
microsoft-foundry

微软代工厂 · Codex、Claude

6,614,144764调用外部服务未明确有提醒
rendering-patterns

渲染模式 · 本页

22034操作浏览器未明确未通过

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

Web Rendering Patterns

Overview

Rendering determines when and where HTML is generated. Each pattern has distinct performance, SEO, and infrastructure implications.

Rendering Pattern Summary

PatternWhen GeneratedWhere GeneratedUse Case
CSRRuntime (browser)ClientDashboards, authenticated apps
SSRRuntime (each request)ServerDynamic, personalized content
SSGBuild timeServer/BuildStatic content, blogs, docs
ISRBuild + revalidationServerContent that changes periodically
StreamingRuntime (progressive)ServerLong pages, slow data sources

Client-Side Rendering (CSR)

Browser generates HTML using JavaScript after page load.

Flow

1. Browser requests page
2. Server returns minimal HTML shell + JS bundle
3. JS executes in browser
4. JS fetches data from API
5. JS renders HTML into DOM

Timeline

Request → Empty Shell → JS Downloads → JS Executes → Data Fetches → Content Visible
         [--------------- Time to Interactive (slow) ---------------]

Characteristics

  • First Contentful Paint (FCP): Slow (waiting for JS)
  • Time to Interactive (TTI): Slow (JS must execute + fetch data)
  • SEO: Poor (crawlers see empty shell unless they execute JS)
  • Server load: Low (static files only)
  • Caching: Easy (static assets)

When to Use

  • Authenticated dashboards (no SEO needed)
  • Highly interactive apps
  • Real-time data that can't be pre-rendered
  • When server infrastructure is limited

Code Pattern

// Pure CSR - data fetched in browser
function ProductPage() {
  const [product, setProduct] = useState(null);

  useEffect(() => {
    fetch('/api/products/123')
      .then(res => res.json())
      .then(setProduct);
  }, []);

  if (!product) return <Loading />;
  return <Product data={product} />;
}

Server-Side Rendering (SSR)

Server generates complete HTML for each request.

Flow

1. Browser requests page
2. Server fetches data
3. Server renders HTML with data
4. Server sends complete HTML
5. Browser displays content immediately
6. JS hydrates for interactivity

Timeline

Request → Server Fetches Data → Server Renders → HTML Sent → Content Visible → Hydration → Interactive
          [--- Server Time ---]                              [--- Hydration ---]

Characteristics

  • FCP: Fast (complete HTML from server)
  • TTI: Depends on hydration time
  • SEO: Excellent (full HTML for crawlers)
  • Server load: High (render on every request)
  • Caching: Complex (varies by user/request)

When to Use

  • SEO-critical pages with dynamic content
  • Personalized content (user-specific)
  • Frequently changing data
  • Pages that need fresh data on every request

Code Pattern (Framework-agnostic concept)

// Server-side: runs on each request
async function renderPage(request) {
  const data = await fetchData(request.params.id);
  const html = renderToString(<Page data={data} />);
  return html;
}

Static Site Generation (SSG)

HTML generated once at build time.

Flow

Build Time:
1. Build process fetches all data
2. Generates HTML for all pages
3. Outputs static files

Runtime:
1. Browser requests page
2. CDN serves pre-built HTML instantly

Timeline

Request → CDN Cache Hit → HTML Delivered → Content Visible (instant)

Characteristics

  • FCP: Fastest (pre-built, CDN-cached)
  • TTI: Fast (minimal JS, or none)
  • SEO: Excellent (complete HTML)
  • Server load: None at runtime (static files)
  • Caching: Trivial (immutable until next build)

When to Use

  • Blogs, documentation, marketing pages
  • Content that changes infrequently
  • Pages where all possible URLs are known at build time
  • Maximum performance is required

Limitations

  • Content stale until rebuild
  • Build time grows with page count
  • Can't handle dynamic routes unknown at build time
  • Personalization requires client-side hydration

Incremental Static Regeneration (ISR)

SSG with automatic background regeneration.

Flow

1. Initial build generates static pages
2. Pages served from cache
3. After revalidation time expires:
   - Serve stale page (fast)
   - Regenerate in background
   - Next request gets fresh page

Revalidation Strategies

Time-based:

Page generated → Serve for 60 seconds → Regenerate on next request after 60s

On-demand:

CMS publishes → Webhook triggers regeneration → Page updated immediately

Characteristics

  • FCP: Fast (cached HTML)
  • Freshness: Configurable (seconds to hours)
  • SEO: Excellent
  • Server load: Low (regenerate occasionally)
  • Scalability: High (mostly static)

When to Use

  • E-commerce product pages
  • News sites
  • Content that updates but not real-time
  • High-traffic pages that need freshness

Streaming / Progressive Rendering

Server sends HTML in chunks as data becomes available.

Flow

1. Browser requests page
2. Server immediately sends HTML shell
3. Server fetches data (possibly in parallel)
4. Server streams HTML chunks as ready
5. Browser renders progressively

Timeline

Request → Shell Sent → [Chunk 1 Streams] → [Chunk 2 Streams] → Complete
          [Visible]    [More Visible]      [Fully Visible]

Characteristics

  • FCP: Very fast (shell immediate)
  • TTFB: Fast (no waiting for all data)
  • User Experience: Progressive disclosure
  • Complexity: Higher implementation

When to Use

  • Pages with multiple data sources
  • Slow API dependencies
  • Long pages where top should render first
  • Improving perceived performance

Rendering Decision Flowchart

Does the page need SEO?
├── No → Does it need real-time data?
│        ├── Yes → CSR
│        └── No → SSG or CSR
│
└── Yes → Is content the same for all users?
          ├── Yes → Does content change often?
          │         ├── Rarely → SSG
          │         ├── Sometimes → ISR
          │         └── Every request → SSR
          │
          └── No (personalized) → SSR with caching strategies

Hybrid Approaches

Modern apps mix patterns per route:

RoutePatternReason
/ (home)SSGStatic marketing content
/blog/*SSG/ISRContent changes occasionally
/products/*ISRPrices update, need SEO
/dashboardCSRAuthenticated, no SEO
/searchSSRDynamic query results

Performance Metrics Impact

PatternTTFBFCPLCPTTI
CSRFastSlowSlowSlow
SSRSlowerFastFastMedium
SSGFastestFastestFastestFast
ISRFastestFastestFastestFast
StreamingFastFastProgressiveMedium

Deep Dive: Understanding How Rendering Actually Works

What Does "Rendering" Actually Mean?

Rendering is the process of converting your application code into HTML that a browser can display. Understanding this deeply requires knowing what happens at each layer.

The Rendering Pipeline:

Your Code (JSX, Vue template, Svelte)
        ↓
Framework Virtual Representation (Virtual DOM, reactive graph)
        ↓
HTML String or DOM Operations
        ↓
Browser's DOM Tree
        ↓
Browser's Render Tree (DOM + CSS)
        ↓
Layout (position, size calculations)
        ↓
Paint (pixels on screen)
        ↓
Composite (layers combined)

When we say "server rendering" vs "client rendering", we're talking about WHERE the first few steps happen.

The Fundamental Trade-off: Work Location

Every web page requires work to be done. The question is: who does the work?

SERVER RENDERING:
┌─────────────────────────────────────────────────────────────────┐
│ SERVER (powerful, shared)                                       │
│                                                                 │
│  [Fetch Data] → [Build HTML String] → [Send HTML]              │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘
                                          │
                                          ▼
┌─────────────────────────────────────────────────────────────────┐
│ CLIENT (varies, individual)                                     │
│                                                                 │
│  [Parse HTML] → [Build DOM] → [Display]                        │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘

CLIENT RENDERING:
┌─────────────────────────────────────────────────────────────────┐
│ SERVER (powerful, shared)                                       │
│                                                                 │
│  [Send static JS bundle]                                        │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘
                                          │
                                          ▼
┌─────────────────────────────────────────────────────────────────┐
│ CLIENT (varies, individual)                                     │
│                                                                 │
│  [Download JS] → [Execute JS] → [Fetch Data] → [Build DOM]     │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘

Server rendering: Server does more work, client does less Client rendering: Server does less work, client does more

How Server-Side Rendering Works Internally

When a server renders HTML, it runs your component code to produce a string:

// What your React component looks like
function ProductPage({ product }) {
  return (
    <div className="product">
      <h1>{product.name}</h1>
      <p>${product.price}</p>
    </div>
  );
}

// What the server actually does (simplified)
function renderToString(component) {
  // 1. Execute component function
  const virtualDOM = component({ product: { name: 'Shoes', price: 99 } });

  // 2. virtualDOM is a tree structure:
  // {
  //   type: 'div',
  //   props: { className: 'product' },
  //   children: [
  //     { type: 'h1', children: ['Shoes'] },
  //     { type: 'p', children: ['$99'] }
  //   ]
  // }

  // 3. Convert tree to HTML string
  return '<div class="product"><h1>Shoes</h1><p>$99</p></div>';
}

The server runs JavaScript to produce HTML. It's executing your React/Vue/Svelte code, but instead of updating a browser DOM, it builds a string.

How Client-Side Rendering Works Internally

CSR works differently - it manipulates the live DOM:

// Browser receives empty HTML:
// <div id="root"></div>

// JavaScript bundle executes:
const root = document.getElementById('root');

// Framework creates elements and appends them
const div = document.createElement('div');
div.className = 'product';

const h1 = document.createElement('h1');
h1.textContent = 'Shoes';

const p = document.createElement('p');
p.textContent = '$99';

div.appendChild(h1);
div.appendChild(p);
root.appendChild(div);

// Each DOM operation triggers browser work

Every DOM manipulation can trigger layout and paint. This is why virtual DOM exists - to batch changes.

Why SSG is Fastest: CDN Edge Caching

Static Site Generation's speed comes from CDN distribution:

Traditional SSR:
User (Tokyo) → Request → Origin Server (New York) → Process → Response
              [───────────── 200-500ms ──────────────]

Static + CDN:
User (Tokyo) → Request → CDN Edge (Tokyo) → Cache Hit → Response
              [──────────── 20-50ms ────────────]

How CDNs Work:

First Request (cache miss):
1. User requests /products
2. CDN edge has no cache
3. Request goes to origin
4. Origin returns HTML
5. CDN caches it
6. User receives response

Subsequent Requests (cache hit):
1. User requests /products
2. CDN edge has cached HTML
3. Immediate response (no origin contact)

With SSG, the HTML is pre-built and distributed to CDN edges worldwide BEFORE any user requests it.

ISR: How Stale-While-Revalidate Works

ISR combines caching with freshness. Understanding the timeline is key:

Build Time: Page generated, cached with revalidate: 60

Timeline:
[0s]     Page built, served to all users
[30s]    User A requests → Gets cached page (age: 30s, still fresh)
[60s]    Page is now "stale" but still cached
[61s]    User B requests → Gets stale page immediately
         Background: Server regenerates page
[62s]    New page ready, replaces old in cache
[70s]    User C requests → Gets fresh page (age: 8s)

The key insight: the user who triggers revalidation gets the stale page. The NEXT user gets fresh content. This is "stale-while-revalidate" strategy.

Streaming: How HTTP Chunked Transfer Works

Streaming isn't magic - it uses HTTP's chunked transfer encoding:

Normal Response:
HTTP/1.1 200 OK
Content-Length: 5000

[...waits until all 5000 bytes ready...]
[...sends all at once...]

Chunked/Streaming Response:
HTTP/1.1 200 OK
Transfer-Encoding: chunked

100                          ← Chunk size in hex (256 bytes)
<html><head>...</head><body> ← Actual content
0                            ← More chunks coming

200                          ← Next chunk (512 bytes)
<main>Content here...</main>
0

0                            ← Final chunk (0 means done)

The browser can start rendering BEFORE the full response arrives.

React Streaming Example:

// Server Component
async function Page() {
  return (
    <html>
      <body>
        <Header />  {/* Immediate - no data */}

        <Suspense fallback={<LoadingSkeleton />}>
          <SlowDataComponent />  {/* Streams when ready */}
        </Suspense>

        <Footer />  {/* Immediate - no data */}
      </body>
    </html>
  );
}

// What gets streamed:
// Chunk 1: <html><body><Header>...</Header><LoadingSkeleton />
// [... server fetching SlowDataComponent data ...]
// Chunk 2: <script>swapContent('slow-component', '<SlowData>...</SlowData>')</script>
// Chunk 3: <Footer>...</Footer></body></html>

Time to First Byte (TTFB) vs Time to Last Byte

Understanding these metrics clarifies rendering tradeoffs:

CSR Request:
[Request]─────[TTFB: 50ms]─────[TTLB: 100ms]
              Small static file, fast to send

SSR Request (blocking):
[Request]─────────────────────[TTFB: 500ms]─────[TTLB: 520ms]
              Server processing delays first byte

SSR Request (streaming):
[Request]───[TTFB: 50ms]─────────────────────────[TTLB: 500ms]
            Shell immediate      Content streams progressively

Streaming improves TTFB dramatically while allowing complex server work.

The N+1 Problem in Rendering

Both SSR and CSR can suffer from N+1 data fetching:

// Waterfall problem
async function ProductsPage() {
  const products = await fetch('/api/products');  // 1 request

  return products.map(product => (
    <Product
      product={product}
      reviews={await fetch(`/api/reviews/${product.id}`)}  // N requests
    />
  ));
}

// If you have 50 products = 51 requests (serial!)
// Each awaits the previous = massive latency

Solution - Parallel fetching:

async function ProductsPage() {
  const products = await fetch('/api/products');

  // Fetch all reviews in parallel
  const reviewsPromises = products.map(p =>
    fetch(`/api/reviews/${p.id}`)
  );
  const reviews = await Promise.all(reviewsPromises);

  // Now render with all data
}

Cache Invalidation: The Hard Problem

"There are only two hard things in Computer Science: cache invalidation and naming things."

Problem Scenario:
1. Page generated with product price $99
2. Price changes to $89 in database
3. Cached page still shows $99
4. User sees wrong price

Cache Strategies:

TIME-BASED (ISR):
- Revalidate every 60 seconds
- Pros: Simple, predictable
- Cons: Up to 60s stale data

EVENT-BASED (On-demand revalidation):
- CMS webhook triggers rebuild
- Pros: Immediate freshness
- Cons: Complex, webhook reliability

CACHE TAGS:
- Tag pages by dependency: ['product-123', 'category-shoes']
- Invalidate by tag when data changes
- Pros: Precise invalidation
- Cons: Complex dependency tracking

Edge Rendering vs Origin Rendering

Modern architectures introduce edge computing:

ORIGIN RENDERING (traditional SSR):
User → CDN Edge → Origin Server (single location) → Response
       [20ms]     [─────── 200ms ───────]

EDGE RENDERING:
User → CDN Edge (runs your code) → Response
       [──────── 50ms ───────]
       No origin round-trip needed

EDGE + ORIGIN:
User → Edge (static parts) → Origin (dynamic parts)
       [──── 50ms ────]     [─── 150ms for dynamic ───]
       Shell immediate       Data streams in

Edge functions run your server code geographically close to users. Platforms like Cloudflare Workers, Vercel Edge, Deno Deploy enable this.

Memory and CPU: The Rendering Costs

CSR Memory Pattern:

Browser Memory Over Time:
[Page Load] → [JS Parsed: 50MB heap] → [App Runs: 80MB] → [Navigation: 100MB] → ...
                                       Memory grows, garbage collected periodically
                                       Memory leaks possible if state not cleaned

SSR Memory Pattern:

Server Memory Per Request:
[Request] → [Render: 20MB allocated] → [Response Sent] → [Memory freed]
            Fresh start each request
            No memory leaks across requests
            But: concurrent requests = concurrent memory

CPU Considerations:

CSR: Each user's device does rendering work
     1000 users = 1000 CPUs doing work (distributed)

SSR: Server does all rendering work
     1000 users = 1 server CPU doing 1000x work (concentrated)

Solution: Caching (SSG/ISR) or scaling servers

When to Use What: Deep Analysis

Choose CSR when:

  • Users are authenticated (can't cache anyway)
  • Data is real-time (WebSockets, polling)
  • Heavy interactivity (dashboards, editors)
  • Server costs must be minimal
  • SEO doesn't matter

Choose SSR when:

  • SEO is critical AND data is dynamic
  • Personalization needed (user-specific content)
  • Data changes every request
  • You can handle server costs
  • First paint must include real content

Choose SSG when:

  • Content changes rarely (docs, blogs)
  • All URLs known at build time
  • Maximum performance needed
  • Minimal server infrastructure
  • Content is same for all users

Choose ISR when:

  • Content changes but not constantly
  • SEO needed but data updates
  • Can tolerate brief staleness
  • Want SSG benefits with some dynamism

Choose Streaming when:

  • Parts of page have slow data dependencies
  • Want fast first paint with SSR
  • Page has mixed static/dynamic content
  • User experience during load matters

For Framework Authors: Implementing Rendering Systems

Implementation Note: The patterns and code examples below represent one proven approach to building rendering systems. There are many valid implementation strategies—the direction shown here is based on patterns from React, Preact, Solid, and other frameworks. Your implementation may differ based on your virtual DOM design, component model, and performance goals. Use these as architectural guidance rather than prescriptive solutions.

Building a Server-Side Renderer

Core SSR implementation for React-like frameworks:

// MINIMAL SSR IMPLEMENTATION

// 1. Component to HTML string conversion
function renderToString(element) {
  if (typeof element === 'string' || typeof element === 'number') {
    return escapeHtml(String(element));
  }

  if (element === null || element === undefined || element === false) {
    return '';
  }

  if (Array.isArray(element)) {
    return element.map(renderToString).join('');
  }

  const { type, props } = element;

  // Function component
  if (typeof type === 'function') {
    const result = type(props);
    return renderToString(result);
  }

  // HTML element
  const attributes = renderAttributes(props);
  const children = renderToString(props.children);

  // Void elements (no closing tag)
  if (VOID_ELEMENTS.has(type)) {
    return `<${type}${attributes}>`;
  }

  return `<${type}${attributes}>${children}</${type}>`;
}

function renderAttributes(props) {
  return Object.entries(props || {})
    .filter(([key]) => key !== 'children' && !key.startsWith('on'))
    .map(([key, value]) => {
      if (key === 'className') key = 'class';
      if (key === 'htmlFor') key = 'for';
      if (typeof value === 'boolean') {
        return value ? ` ${key}` : '';
      }
      return ` ${key}="${escapeHtml(String(value))}"`;
    })
    .join('');
}

// 2. Full HTML document wrapper
function renderDocument(app, { head, scripts, styles }) {
  return `<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  ${head}
  ${styles.map(s => `<link rel="stylesheet" href="${s}">`).join('\n')}
</head>
<body>
  <div id="app">${app}</div>
  ${scripts.map(s => `<script src="${s}"></script>`).join('\n')}
</body>
</html>`;
}

// 3. Server handler
async function handleSSR(request) {
  const url = new URL(request.url);
  const route = matchRoute(url.pathname);

  // Fetch data on server
  const data = await route.loader?.({ request, params: route.params });

  // Render component tree
  const app = renderToString(
    createElement(route.component, { data })
  );

  // Serialize data for hydration
  const serializedData = `<script>window.__DATA__=${JSON.stringify(data)}</script>`;

  const html = renderDocument(app, {
    head: renderHead(route),
    scripts: ['/client.js'],
    styles: ['/styles.css'],
  }) + serializedData;

  return new Response(html, {
    headers: { 'Content-Type': 'text/html' },
  });
}

Implementing Streaming SSR

// STREAMING SSR IMPLEMENTATION

async function* renderToStream(element, context) {
  // Yield shell immediately
  yield '<!DOCTYPE html><html><head></head><body><div id="app">';

  // Render with suspense boundaries
  yield* renderWithSuspense(element, context);

  // Yield closing tags
  yield '</div></body></html>';
}

async function* renderWithSuspense(element, context) {
  if (element.type === Suspense) {
    const suspenseId = context.nextSuspenseId++;

    // Yield fallback immediately
    yield `<template id="S:${suspenseId}">`;
    yield renderToString(element.props.fallback);
    yield `</template>`;

    // Start async work
    context.pendingBoundaries.push({
      id: suspenseId,
      promise: renderChildren(element.props.children, context),
    });

    return;
  }

  // Regular element - render synchronously
  yield renderToString(element);
}

// Stream pending boundaries as they complete
async function* flushPendingBoundaries(context) {
  while (context.pendingBoundaries.length > 0) {
    const completed = await Promise.race(
      context.pendingBoundaries.map(b =>
        b.promise.then(html => ({ id: b.id, html }))
      )
    );

    // Remove from pending
    context.pendingBoundaries = context.pendingBoundaries.filter(
      b => b.id !== completed.id
    );

    // Yield swap script
    yield `<script>
      const template = document.getElementById('S:${completed.id}');
      const content = document.createElement('div');
      content.innerHTML = ${JSON.stringify(completed.html)};
      template.replaceWith(content.firstChild);
    </script>`;
  }
}

// HTTP handler with streaming
async function handleStreamingSSR(request) {
  const stream = new ReadableStream({
    async start(controller) {
      const context = {
        nextSuspenseId: 0,
        pendingBoundaries: [],
      };

      // Stream initial content
      for await (const chunk of renderToStream(<App />, context)) {
        controller.enqueue(new TextEncoder().encode(chunk));
      }

      // Stream pending boundaries
      for await (const chunk of flushPendingBoundaries(context)) {
        controller.enqueue(new TextEncoder().encode(chunk));
      }

      controller.close();
    },
  });

  return new Response(stream, {
    headers: {
      'Content-Type': 'text/html',
      'Transfer-Encoding': 'chunked',
    },
  });
}

Building a Static Site Generator

// STATIC SITE GENERATOR IMPLEMENTATION

async function buildStaticSite(config) {
  const routes = await discoverRoutes(config.pagesDir);
  const outputDir = config.outputDir;

  // Parallel build with concurrency limit
  const limit = pLimit(10);

  await Promise.all(
    routes.map(route =>
      limit(async () => {
        console.log(`Building ${route.path}...`);

        // For dynamic routes, get all possible values
        if (route.isDynamic) {
          const paths = await route.getStaticPaths();
          await Promise.all(
            paths.map(p => buildPage(route, p, outputDir))
          );
        } else {
          await buildPage(route, {}, outputDir);
        }
      })
    )
  );

  // Copy static assets
  await copyDir(config.publicDir, outputDir);

  // Generate sitemap
  await generateSitemap(routes, outputDir);
}

async function buildPage(route, params, outputDir) {
  // Fetch data at build time
  const data = await route.loader?.({ params });

  // Render to string
  const html = renderToString(
    createElement(route.component, { data, params })
  );

  // Wrap in document
  const fullHtml = renderDocument(html, {
    head: renderHead(route, data),
    scripts: route.hasInteractivity ? ['/hydrate.js'] : [],
    styles: ['/styles.css'],
  });

  // Write to file
  const filePath = path.join(outputDir, route.path, 'index.html');
  await mkdir(path.dirname(filePath), { recursive: true });
  await writeFile(filePath, fullHtml);
}

Implementing ISR (Incremental Static Regeneration)

// ISR IMPLEMENTATION

class ISRCache {
  constructor() {
    this.cache = new Map();
    this.regenerating = new Set();
  }

  async get(key, regenerate, { revalidate = 60 }) {
    const entry = this.cache.get(key);
    const now = Date.now();

    if (entry) {
      const age = (now - entry.timestamp) / 1000;

      // Fresh - return cached
      if (age < revalidate) {
        return { html: entry.html, status: 'HIT' };
      }

      // Stale - return cached but regenerate in background
      if (!this.regenerating.has(key)) {
        this.regenerating.add(key);
        this.regenerateInBackground(key, regenerate);
      }

      return { html: entry.html, status: 'STALE' };
    }

    // Miss - generate synchronously
    const html = await regenerate();
    this.cache.set(key, { html, timestamp: now });

    return { html, status: 'MISS' };
  }

  async regenerateInBackground(key, regenerate) {
    try {
      const html = await regenerate();
      this.cache.set(key, { html, timestamp: Date.now() });
    } finally {
      this.regenerating.delete(key);
    }
  }

  // On-demand revalidation
  revalidate(key) {
    this.cache.delete(key);
  }

  // Revalidate by tag
  revalidateTag(tag) {
    for (const [key, entry] of this.cache) {
      if (entry.tags?.includes(tag)) {
        this.cache.delete(key);
      }
    }
  }
}

// HTTP handler with ISR
const isrCache = new ISRCache();

async function handleISR(request) {
  const url = new URL(request.url);
  const route = matchRoute(url.pathname);

  const { html, status } = await isrCache.get(
    url.pathname,
    async () => {
      const data = await route.loader({ request });
      return renderToString(createElement(route.component, { data }));
    },
    { revalidate: route.revalidate || 60 }
  );

  return new Response(html, {
    headers: {
      'Content-Type': 'text/html',
      'X-Cache-Status': status,
      'Cache-Control': `s-maxage=${route.revalidate}, stale-while-revalidate`,
    },
  });
}

Edge Rendering Architecture

// EDGE RENDERING IMPLEMENTATION

// Edge-compatible rendering (V8 isolates)
export default {
  async fetch(request, env, ctx) {
    const url = new URL(request.url);

    // Check edge cache first
    const cacheKey = new Request(url.toString(), request);
    const cache = caches.default;
    let response = await cache.match(cacheKey);

    if (!response) {
      // Render at edge
      const html = await renderPage(url.pathname, {
        // Edge has access to geolocation
        country: request.cf?.country,
        city: request.cf?.city,
      });

      response = new Response(html, {
        headers: {
          'Content-Type': 'text/html',
          'Cache-Control': 's-maxage=60',
        },
      });

      // Cache at edge
      ctx.waitUntil(cache.put(cacheKey, response.clone()));
    }

    return response;
  },
};

// Personalization at the edge
async function renderPage(pathname, context) {
  const route = matchRoute(pathname);

  // Personalize based on location
  const data = await route.loader({
    country: context.country,
    locale: countryToLocale(context.country),
  });

  return renderToString(createElement(route.component, { data }));
}

Related Skills

平台分布

Codex

37.84%
按下载量换算27

Claude

27.54%
按下载量换算20

Cursor

18.86%
按下载量换算13

Gemini CLI

9.16%
按下载量换算7

安全审计

Gen Agent Trust Hub

未通过

Socket

通过

Snyk

通过

权限和风险

操作浏览器

该 Skill 可能涉及浏览器控制能力,使用时可能读取或操作网页内容,需要在受控环境中确认权限边界。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。来源安全扫描存在提醒或未通过项,安装前请自行复核。目前只有一个公开来源,建议同时核对源仓库。

继续浏览同类 Skills