Skip to content

perf(pages): lazy-load documentation content by language - #1896

Closed
YaoSong808 wants to merge 1 commit into
alibaba:mainfrom
YaoSong808:perf/lazy-load-doc-languages
Closed

YaoSong808 wants to merge 1 commit into
alibaba:mainfrom
YaoSong808:perf/lazy-load-doc-languages

Conversation

@YaoSong808

Copy link
Copy Markdown

Description

Split documentation Markdown into one lazy-loaded bundle per supported language while keeping directory metadata in the documentation route chunk.

  • cache successful language loads and share concurrent requests
  • keep failed loads retryable and ignore stale page/search responses
  • preserve English fallback for partial locales without speculative downloads
  • keep the navigation shell visible during loading and expose retry actions
  • preserve full-text search behavior, fragments, SPA navigation, and browser history

Production and cold-cache evidence

Measured on /docs/quickstart in Chinese from the same production build setup:

Uncompressed documentation JavaScript Compressed response bodies
Before 1,526,047 bytes 411,847 bytes
After 263,713 bytes (docs-page + docs-content-zh) 96,066 bytes

This reduces the cold documentation payload by about 76.7% using actual compressed response-body sizes. After the page settled, the browser had fetched only docs-content-zh; en, ja, ko, and ru were absent. SPA navigation from QuickStart to Installation reused the same language bundle without another content request. Switching to English fetched only the English bundle.

Type of Change

  • Bug fix (non-breaking change that fixes an issue)
  • New feature (non-breaking change that adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Refactoring (no functional changes)
  • Documentation update
  • CI / Build / Tooling

How Has This Been Tested?

  • make test passes locally
  • Manual testing (described above)

Automated checks:

  • make check
  • npm --prefix pages run lint (passes with two pre-existing hook warnings)
  • npm --prefix pages test (13 files, 61 tests)
  • npm --prefix pages run typecheck
  • npm --prefix pages run build (passes with existing asset/entrypoint size warnings)
  • npm --prefix pages run size (96.97 kB brotlied, 150 kB limit)

Checklist

  • My code follows the project's coding style (go fmt, go vet)
  • I have performed a self-review of my code
  • I have added tests that prove my fix is effective or my feature works
  • New and existing unit tests pass locally with my changes
  • I have updated the documentation accordingly (if applicable)
  • I have signed the CLA
  • I did not use AI/LLM to create this PR, or I disclosed the tool/model below and reviewed its output; I did not attribute commits to AI and will answer maintainer questions and review comments myself without AI/LLM.

AI/LLM disclosure: OpenAI Codex (GPT-5) assisted with repository inspection, implementation, tests, browser verification, and PR preparation. The contributor will review and understand the complete diff before marking this draft ready for review, and will answer maintainer questions personally.

Related Issues

Closes #1895

@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@github-actions

github-actions Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

🔍 OpenCodeReview found 7 issue(s) in this PR.

  • ✅ Successfully posted inline: 7 comment(s)


export type DocDirectory = readonly DocDirectoryEntry[];

const ALL_LANGUAGES: readonly Language[] = ['en', 'zh', 'ja', 'ko', 'ru'];

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maintainability · medium
ALL_LANGUAGES duplicates the identical list already defined as SUPPORTED_LANGUAGES in index.ts (and also in i18n/context.tsx). If a new language is added to one list but not the others, the directory and the runtime normalization will silently disagree — the directory would claim a language is available while normalizeLanguage falls back to English, or vice versa. Consider exporting a single canonical list (e.g., from i18n/types or a shared constants module) and importing it in all three locations.

Comment on lines +54 to +55
const match = markdown.slice(3, end).match(/title:\s*(.+)/);
if (match) return match[1].trim();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
The titleFromFrontmatter regex /title:\s*(.+)/ does not strip surrounding quotes from YAML values. If any document uses quoted frontmatter like title: "My Title" or title: 'My Title', the extracted title will include the quote characters, resulting in malformed display.

While current markdown files use unquoted titles, this is fragile and could silently break when new documents are added.

Suggestion:

Suggested change
const match = markdown.slice(3, end).match(/title:\s*(.+)/);
if (match) return match[1].trim();
const match = markdown.slice(3, end).match(/title:\s*["']?(.+?)["']?\s*$/m);
if (match) return match[1].trim();

for (const entry of directory) {
const raw = hasTranslation(entry, language)
? contentFor(localized, entry.slug, language)
: contentFor(english!, entry.slug, 'en');

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maintainability · low
The non-null assertion english! is safe only because of an invariant established by the needsEnglish check above: if any entry lacks a translation, English is loaded. However, this coupling between two separate iterations over directory is fragile — a future refactor that changes one without the other could introduce a runtime crash. Consider restructuring to make the dependency explicit, e.g., by always loading English when language !== 'en', or by resolving the fallback bundle per-entry.

return () => {
active = false;
};
}, [language, requestKey, runSearch, searchQuery]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maintainability · low
The useEffect dependency array includes both requestKey and its constituent values (language, searchQuery). Since requestKey is derived as ${language}:${searchQuery}:${searchAttempt}, listing language and searchQuery separately is redundant — any change to them already changes requestKey. Consider using only [requestKey, runSearch] to avoid confusion about intended trigger semantics, or remove requestKey and keep the individual values (but then add searchAttempt).

export function useDocPage(
slug: DocSlug,
language: string,
loader: DocPageLoader = loadDocPage,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · low
Using a default parameter (loader = loadDocPage) means that when callers omit the argument, the default value is re-evaluated on every render. While loadDocPage is a stable module-level reference so this works correctly in practice, it creates a subtle trap: if someone later passes undefined explicitly (e.g., from an optional prop), React's dependency tracking in the useEffect below will see undefined as the dependency rather than the resolved default, potentially causing unnecessary re-runs or missed updates. Consider resolving the default inside the function body instead:

const resolvedLoader = loader ?? loadDocPage;

and using resolvedLoader in the effect and its dependency array.

return () => {
active = false;
};
}, [language, loader, requestKey, slug]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maintainability · low
Same redundant dependency pattern as useCommandSearch: requestKey already encodes language and slug, so listing them separately is unnecessary. Use either [requestKey, loader] or [language, slug, attempt, loader] consistently.

Comment on lines +210 to 214
const navigateToDoc = useCallback((slug: DocSlug, fragment?: string) => {
navigate(`/docs/${slug}${fragment ? `#${fragment}` : ''}`);
// Scroll page to top
window.scrollTo(0, 0);
}, [navigate]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
When navigateToDoc is called with a fragment (e.g., from cross-doc link clicks), window.scrollTo(0, 0) runs synchronously before the async content loads and the fragment-scrolling useEffect fires. This causes a visible flash: the page jumps to the top, then later scrolls to the target heading once content arrives. Consider skipping the scroll-to-top when a fragment is provided, since the fragment-scroll effect will handle positioning.

Suggestion:

Suggested change
const navigateToDoc = useCallback((slug: DocSlug, fragment?: string) => {
navigate(`/docs/${slug}${fragment ? `#${fragment}` : ''}`);
// Scroll page to top
window.scrollTo(0, 0);
}, [navigate]);
const navigateToDoc = useCallback((slug: DocSlug, fragment?: string) => {
navigate(`/docs/${slug}${fragment ? `#${fragment}` : ''}`);
if (!fragment) {
window.scrollTo(0, 0);
}
}, [navigate]);

@Qiyuanqiii Qiyuanqiii left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

签署一下CLA谢谢

@lizhengfeng101

Copy link
Copy Markdown
Contributor

Thank you for working on this optimization. This PR is still a draft, with no follow-up commits or author responses since the initial submission and CLA reminder on November 10, and the CLA check remains pending. We are closing the current draft for now.

This does not reject the underlying request to lazy-load documentation by language. When you are ready to continue, please complete your self-review and CLA, respond to the review feedback, update the branch against current main, and ask to reopen this PR or submit a refreshed one.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

perf(pages): lazy-load documentation content by language

4 participants