0
# Extension System
1
2
MathJax uses a modular component system that allows loading input processors, output processors, and specialized extensions on demand. This provides flexibility in customizing functionality while keeping bundle sizes optimized.
3
4
## Capabilities
5
6
### Component Loading
7
8
Load MathJax components dynamically based on requirements.
9
10
```javascript { .api }
11
/**
12
* Load specified components
13
* @param components - List of component names to load
14
* @returns Promise that resolves when all components are loaded
15
*/
16
function load(...components: string[]): Promise<any[]>;
17
18
/**
19
* Mark components as pre-loaded
20
* @param components - List of component names to mark as loaded
21
*/
22
function preLoaded(...components: string[]): void;
23
24
/**
25
* Check component version compatibility
26
* @param component - Component name
27
* @param version - Required version
28
* @param name - Component display name
29
* @returns Whether version is compatible
30
*/
31
function checkVersion(component: string, version: string, name: string): boolean;
32
33
/**
34
* Get root path for component loading
35
* @returns Root path string
36
*/
37
function getRoot(): string;
38
```
39
40
**Usage Examples:**
41
42
```javascript
43
// Load individual components
44
await MathJax.loader.load('input/tex', 'output/svg');
45
46
// Load multiple components
47
await MathJax.loader.load(
48
'input/tex',
49
'[tex]/ams',
50
'[tex]/color',
51
'output/chtml',
52
'a11y/semantic-enrich'
53
);
54
55
// Mark components as pre-loaded (for bundled components)
56
MathJax.loader.preLoaded('startup', 'core');
57
58
// Check version compatibility
59
const isCompatible = MathJax.loader.checkVersion('input/tex', '4.0.0', 'TeX Input');
60
61
// Get component root path
62
const rootPath = MathJax.loader.getRoot();
63
```
64
65
### Extension Configuration
66
67
Configure which components to load through the loader configuration.
68
69
```javascript { .api }
70
interface LoaderOptions {
71
/** Components to load automatically */
72
load?: string[];
73
/** Component dependencies */
74
dependencies?: Record<string, string[]>;
75
/** Path mappings for component loading */
76
paths?: Record<string, string>;
77
/** Source file mappings */
78
source?: Record<string, string>;
79
/** Components provided by other components */
80
provides?: Record<string, string[]>;
81
}
82
```
83
84
**Configuration Examples:**
85
86
```javascript
87
// Basic component loading
88
MathJax.config.loader = {
89
load: ['input/tex', '[tex]/ams', 'output/chtml']
90
};
91
92
// Advanced configuration with custom paths
93
MathJax.config.loader = {
94
load: ['input/tex', 'output/svg', 'ui/menu'],
95
paths: {
96
mathjax: 'https://cdn.jsdelivr.net/npm/mathjax@4',
97
custom: 'https://my-cdn.com/mathjax-extensions'
98
},
99
dependencies: {
100
'custom/myextension': ['input/tex']
101
}
102
};
103
```
104
105
## Available Components
106
107
### Input Components
108
109
Process different mathematical notation formats.
110
111
**Core Input Processors:**
112
- **`input/tex`** - Complete TeX/LaTeX processor with extensions
113
- **`input/tex-base`** - Basic TeX processor without extensions
114
- **`input/mml`** - MathML processor
115
- **`input/asciimath`** - AsciiMath processor
116
117
**Usage Examples:**
118
119
```javascript
120
// Load TeX with extensions
121
MathJax.config.loader.load = ['input/tex'];
122
123
// Load basic TeX only
124
MathJax.config.loader.load = ['input/tex-base'];
125
126
// Load multiple input formats
127
MathJax.config.loader.load = ['input/tex', 'input/mml', 'input/asciimath'];
128
```
129
130
### Output Components
131
132
Render mathematics in different formats.
133
134
**Available Output Processors:**
135
- **`output/chtml`** - CommonHTML output (HTML/CSS)
136
- **`output/svg`** - SVG output (Scalable Vector Graphics)
137
138
**Usage Examples:**
139
140
```javascript
141
// Use CommonHTML output
142
MathJax.config.loader.load = ['input/tex', 'output/chtml'];
143
144
// Use SVG output
145
MathJax.config.loader.load = ['input/tex', 'output/svg'];
146
147
// Both outputs available (choose at conversion time)
148
MathJax.config.loader.load = ['input/tex', 'output/chtml', 'output/svg'];
149
```
150
151
### TeX Extensions
152
153
Extend TeX/LaTeX functionality with specialized packages.
154
155
**Core Extensions:**
156
- **`[tex]/ams`** - AMS math environments and symbols
157
- **`[tex]/amscd`** - AMS commutative diagrams
158
- **`[tex]/newcommand`** - Define custom commands
159
- **`[tex]/color`** - Color support
160
161
**Mathematical Extensions:**
162
- **`[tex]/boldsymbol`** - Bold mathematical symbols
163
- **`[tex]/braket`** - Dirac bra-ket notation
164
- **`[tex]/cancel`** - Cancel expressions with lines
165
- **`[tex]/enclose`** - Enclose expressions with boxes/lines
166
- **`[tex]/mhchem`** - Chemistry notation
167
- **`[tex]/physics`** - Physics notation and operators
168
- **`[tex]/units`** - Unit formatting
169
170
**Formatting Extensions:**
171
- **`[tex]/bbox`** - Bounding boxes and backgrounds
172
- **`[tex]/textmacros`** - Text formatting commands
173
- **`[tex]/unicode`** - Unicode character support
174
- **`[tex]/verb`** - Verbatim text rendering
175
176
**Advanced Extensions:**
177
- **`[tex]/autoload`** - Automatic extension loading
178
- **`[tex]/require`** - Dynamic requirement loading
179
- **`[tex]/configmacros`** - Configuration-based macros
180
181
**Usage Examples:**
182
183
```javascript
184
// Load specific extensions
185
MathJax.config.loader.load = [
186
'input/tex',
187
'[tex]/ams',
188
'[tex]/color',
189
'[tex]/mhchem',
190
'output/chtml'
191
];
192
193
// Load many extensions
194
MathJax.config.loader.load = [
195
'input/tex',
196
'[tex]/ams',
197
'[tex]/amscd',
198
'[tex]/bbox',
199
'[tex]/boldsymbol',
200
'[tex]/braket',
201
'[tex]/cancel',
202
'[tex]/color',
203
'[tex]/enclose',
204
'[tex]/mhchem',
205
'[tex]/physics',
206
'output/svg'
207
];
208
```
209
210
### Accessibility Components
211
212
Enhance mathematical accessibility for assistive technologies.
213
214
**Available Components:**
215
- **`a11y/semantic-enrich`** - Semantic analysis and enrichment
216
- **`a11y/speech`** - Speech generation
217
- **`a11y/explorer`** - Interactive exploration
218
- **`a11y/complexity`** - Mathematical complexity analysis
219
- **`a11y/assistive-mml`** - Assistive MathML generation
220
- **`a11y/sre`** - Speech Rule Engine
221
222
**Usage Examples:**
223
224
```javascript
225
// Full accessibility support
226
MathJax.config.loader.load = [
227
'input/tex',
228
'output/chtml',
229
'a11y/semantic-enrich',
230
'a11y/speech',
231
'a11y/explorer',
232
'a11y/assistive-mml'
233
];
234
235
// Basic accessibility
236
MathJax.config.loader.load = [
237
'input/tex',
238
'output/svg',
239
'a11y/assistive-mml'
240
];
241
```
242
243
### UI Components
244
245
User interface elements and interactions.
246
247
**Available Components:**
248
- **`ui/menu`** - Context menu for mathematical expressions
249
- **`ui/lazy`** - Lazy loading utilities
250
- **`ui/safe`** - Safe mode error handling
251
252
**Usage Examples:**
253
254
```javascript
255
// Add context menu
256
MathJax.config.loader.load = [
257
'input/tex',
258
'output/chtml',
259
'ui/menu'
260
];
261
262
// Safe mode with error handling
263
MathJax.config.loader.load = [
264
'input/tex',
265
'output/svg',
266
'ui/safe'
267
];
268
```
269
270
### Adaptor Components
271
272
DOM adapters for different environments.
273
274
**Available Adaptors:**
275
- **`adaptors/liteDOM`** - Lightweight DOM for server-side
276
- **`adaptors/jsdom`** - jsdom integration
277
- **`adaptors/linkedom`** - LinkedOM integration
278
279
**Usage Examples:**
280
281
```javascript
282
// Node.js with liteDOM
283
MathJax.config.loader.load = [
284
'adaptors/liteDOM',
285
'input/tex',
286
'output/svg'
287
];
288
289
// Node.js with jsdom
290
MathJax.config.loader.load = [
291
'adaptors/jsdom',
292
'input/tex',
293
'output/chtml'
294
];
295
```
296
297
## Pre-built Component Combinations
298
299
### Single Input/Output Combinations
300
301
Ready-to-use combinations for common scenarios.
302
303
**Available Combinations:**
304
- **`tex-chtml.js`** - TeX input + CommonHTML output
305
- **`tex-svg.js`** - TeX input + SVG output
306
- **`mml-chtml.js`** - MathML input + CommonHTML output
307
- **`mml-svg.js`** - MathML input + SVG output
308
309
**No-Font Variants:**
310
- **`tex-chtml-nofont.js`** - TeX + CommonHTML without web fonts
311
- **`tex-svg-nofont.js`** - TeX + SVG without web fonts
312
- **`mml-chtml-nofont.js`** - MathML + CommonHTML without fonts
313
- **`mml-svg-nofont.js`** - MathML + SVG without fonts
314
315
### Multi-Input Combinations
316
317
Support multiple input formats simultaneously.
318
319
**Available Combinations:**
320
- **`tex-mml-chtml.js`** - TeX + MathML inputs + CommonHTML output
321
- **`tex-mml-svg.js`** - TeX + MathML inputs + SVG output
322
323
**Usage Examples:**
324
325
```html
326
<!-- Single format -->
327
<script src="https://cdn.jsdelivr.net/npm/mathjax@4/tex-chtml.js"></script>
328
329
<!-- Multiple formats -->
330
<script src="https://cdn.jsdelivr.net/npm/mathjax@4/tex-mml-svg.js"></script>
331
332
<!-- Without fonts -->
333
<script src="https://cdn.jsdelivr.net/npm/mathjax@4/tex-svg-nofont.js"></script>
334
```
335
336
## Custom Extensions
337
338
### Creating Custom Extensions
339
340
Build custom extensions for specialized mathematical notation.
341
342
```javascript
343
// Define custom extension
344
const MyCustomExtension = {
345
name: 'custom',
346
version: '1.0.0',
347
348
// Extension initialization
349
init(config) {
350
console.log('Custom extension loaded');
351
},
352
353
// Add custom macros
354
macros: {
355
customSymbol: '{\\unicode{x1D4C0}}',
356
myFunction: ['{\\operatorname{#1}}', 1]
357
},
358
359
// Add custom environments
360
environments: {
361
myenvironment: ['\\begin{array}{cc}', '\\end{array}']
362
}
363
};
364
365
// Register custom extension
366
MathJax.config.tex = MathJax.config.tex || {};
367
MathJax.config.tex.packages = MathJax.config.tex.packages || [];
368
MathJax.config.tex.packages.push('custom');
369
370
// Load the extension
371
MathJax.config.loader.source['[tex]/custom'] = 'path/to/my-extension.js';
372
MathJax.config.loader.load.push('[tex]/custom');
373
```
374
375
### Custom Input Processors
376
377
Create input processors for new mathematical formats.
378
379
```javascript
380
// Custom input processor template
381
class CustomInputJax {
382
constructor(config = {}) {
383
this.config = config;
384
}
385
386
// Process input string
387
compile(math, doc) {
388
// Parse custom format
389
const parsed = this.parse(math.math);
390
391
// Convert to internal format
392
return this.convertToInternal(parsed);
393
}
394
395
parse(input) {
396
// Custom parsing logic
397
return { type: 'custom', content: input };
398
}
399
400
convertToInternal(parsed) {
401
// Convert to MathJax internal format
402
return this.createMathML(parsed);
403
}
404
405
createMathML(parsed) {
406
// Generate MathML representation
407
return '<math><mi>' + parsed.content + '</mi></math>';
408
}
409
}
410
411
// Register custom input processor
412
MathJax.startup.registerConstructor('customInput', CustomInputJax);
413
MathJax.startup.useInput('customInput');
414
```
415
416
### Custom Output Processors
417
418
Create output processors for new rendering formats.
419
420
```javascript
421
// Custom output processor template
422
class CustomOutputJax {
423
constructor(config = {}) {
424
this.config = config;
425
}
426
427
// Render mathematics
428
typeset(math, html) {
429
const mathML = math.root;
430
const customHTML = this.renderCustom(mathML);
431
432
math.typesetRoot = html.node('span', {
433
class: 'mjx-custom'
434
}, [customHTML]);
435
436
return math.typesetRoot;
437
}
438
439
renderCustom(mathml) {
440
// Custom rendering logic
441
return this.createCustomElement(mathml);
442
}
443
444
createCustomElement(mathml) {
445
// Generate custom HTML structure
446
return '<span class="custom-math">' + mathml.textContent + '</span>';
447
}
448
449
styleSheet() {
450
// Return custom CSS
451
return `
452
.mjx-custom {
453
font-family: 'Custom Math Font';
454
color: #333;
455
}
456
.custom-math {
457
border: 1px solid #ddd;
458
padding: 2px 4px;
459
}
460
`;
461
}
462
}
463
464
// Register custom output processor
465
MathJax.startup.registerConstructor('customOutput', CustomOutputJax);
466
MathJax.startup.useOutput('customOutput');
467
```
468
469
## Dynamic Extension Loading
470
471
### Runtime Extension Loading
472
473
Load extensions dynamically based on content or user preferences.
474
475
```javascript
476
// Analyze content to determine needed extensions
477
function analyzeContent(content) {
478
const extensions = [];
479
480
if (content.includes('\\ce{')) {
481
extensions.push('[tex]/mhchem');
482
}
483
484
if (content.includes('\\color{')) {
485
extensions.push('[tex]/color');
486
}
487
488
if (content.includes('\\cancel{')) {
489
extensions.push('[tex]/cancel');
490
}
491
492
if (content.includes('\\bra{') || content.includes('\\ket{')) {
493
extensions.push('[tex]/braket');
494
}
495
496
return extensions;
497
}
498
499
// Load extensions dynamically
500
async function processContentWithExtensions(content) {
501
const needed = analyzeContent(content);
502
503
if (needed.length > 0) {
504
await MathJax.loader.load(...needed);
505
}
506
507
// Process content
508
return MathJax.tex2svg(content);
509
}
510
511
// Usage
512
const chemistry = '\\ce{H2O + CO2 -> H2CO3}';
513
const result = await processContentWithExtensions(chemistry);
514
```
515
516
### Conditional Extension Loading
517
518
Load extensions based on environment or user capabilities.
519
520
```javascript
521
// Environment-based loading
522
function loadEnvironmentExtensions() {
523
const extensions = ['input/tex', 'output/chtml'];
524
525
// Add accessibility if screen reader detected
526
if (hasScreenReader()) {
527
extensions.push('a11y/semantic-enrich', 'a11y/speech');
528
}
529
530
// Add menu for desktop browsers
531
if (isDesktop()) {
532
extensions.push('ui/menu');
533
}
534
535
// Add specific adaptors for Node.js
536
if (typeof window === 'undefined') {
537
extensions.push('adaptors/liteDOM');
538
}
539
540
return MathJax.loader.load(...extensions);
541
}
542
543
function hasScreenReader() {
544
return navigator.userAgent.includes('NVDA') ||
545
navigator.userAgent.includes('JAWS') ||
546
window.speechSynthesis;
547
}
548
549
function isDesktop() {
550
return !('ontouchstart' in window);
551
}
552
553
// Load appropriate extensions
554
loadEnvironmentExtensions().then(() => {
555
MathJax.typeset();
556
});
557
```
558
559
## Extension Dependencies
560
561
### Dependency Management
562
563
MathJax automatically manages extension dependencies.
564
565
```javascript
566
// Dependencies are defined in the loader configuration
567
MathJax.config.loader.dependencies = {
568
// AMS package requires newcommand
569
'[tex]/ams': ['input/tex-base', '[tex]/newcommand'],
570
571
// Physics requires AMS
572
'[tex]/physics': ['input/tex-base', '[tex]/ams'],
573
574
// Color extensions
575
'[tex]/colortbl': ['input/tex-base', '[tex]/color'],
576
577
// Accessibility dependencies
578
'a11y/speech': ['a11y/semantic-enrich'],
579
'a11y/explorer': ['a11y/speech']
580
};
581
582
// When you load an extension, dependencies are loaded automatically
583
await MathJax.loader.load('[tex]/physics');
584
// This automatically loads: input/tex-base, [tex]/newcommand, [tex]/ams
585
```
586
587
### Custom Dependencies
588
589
Define dependencies for custom extensions.
590
591
```javascript
592
// Define custom extension dependencies
593
MathJax.config.loader.dependencies['custom/myextension'] = [
594
'input/tex-base',
595
'[tex]/ams',
596
'[tex]/color'
597
];
598
599
// Register custom extension
600
MathJax.config.loader.source['custom/myextension'] = '/path/to/my-extension.js';
601
602
// Load with automatic dependency resolution
603
await MathJax.loader.load('custom/myextension');
604
```
605
606
## Performance Optimization
607
608
### Selective Loading
609
610
Load only the components you need to minimize bundle size.
611
612
```javascript
613
// Minimal configuration for basic TeX
614
MathJax.config.loader.load = [
615
'input/tex-base', // Basic TeX without extensions
616
'output/chtml' // Lightweight output
617
];
618
619
// Full-featured configuration
620
MathJax.config.loader.load = [
621
'input/tex', // TeX with common extensions
622
'[tex]/ams', // Mathematical extensions
623
'[tex]/color', // Color support
624
'output/svg', // High-quality output
625
'ui/menu', // User interface
626
'a11y/assistive-mml' // Basic accessibility
627
];
628
```
629
630
### Bundle Optimization
631
632
Use pre-built bundles for common combinations.
633
634
```javascript
635
// Instead of loading individual components
636
MathJax.config.loader.load = [
637
'input/tex',
638
'[tex]/ams',
639
'[tex]/newcommand',
640
'[tex]/textmacros',
641
'[tex]/noundefined',
642
'[tex]/require',
643
'[tex]/autoload',
644
'[tex]/configmacros',
645
'output/chtml'
646
];
647
648
// Use pre-built bundle
649
// <script src="https://cdn.jsdelivr.net/npm/mathjax@4/tex-chtml.js"></script>
650
// This includes all the above components in a single optimized file
651
```
652
653
### Lazy Loading
654
655
Load extensions on demand to improve initial page load.
656
657
```javascript
658
// Core loading
659
const core = ['input/tex-base', 'output/chtml'];
660
await MathJax.loader.load(...core);
661
662
// Initial render with basic features
663
MathJax.typeset();
664
665
// Load additional features as needed
666
const loadExtensions = async (extensions) => {
667
await MathJax.loader.load(...extensions);
668
MathJax.texReset(); // Reset to recognize new extensions
669
MathJax.typeset(); // Re-render with new features
670
};
671
672
// Load on user interaction
673
document.getElementById('load-ams').addEventListener('click', () => {
674
loadExtensions(['[tex]/ams']);
675
});
676
677
document.getElementById('load-chemistry').addEventListener('click', () => {
678
loadExtensions(['[tex]/mhchem']);
679
});
680
```