JavaScript display engine for LaTeX, MathML, and AsciiMath mathematical notation in browsers and Node.js
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
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.
Load MathJax components dynamically based on requirements.
/**
* Load specified components
* @param components - List of component names to load
* @returns Promise that resolves when all components are loaded
*/
function load(...components: string[]): Promise<any[]>;
/**
* Mark components as pre-loaded
* @param components - List of component names to mark as loaded
*/
function preLoaded(...components: string[]): void;
/**
* Check component version compatibility
* @param component - Component name
* @param version - Required version
* @param name - Component display name
* @returns Whether version is compatible
*/
function checkVersion(component: string, version: string, name: string): boolean;
/**
* Get root path for component loading
* @returns Root path string
*/
function getRoot(): string;Usage Examples:
// Load individual components
await MathJax.loader.load('input/tex', 'output/svg');
// Load multiple components
await MathJax.loader.load(
'input/tex',
'[tex]/ams',
'[tex]/color',
'output/chtml',
'a11y/semantic-enrich'
);
// Mark components as pre-loaded (for bundled components)
MathJax.loader.preLoaded('startup', 'core');
// Check version compatibility
const isCompatible = MathJax.loader.checkVersion('input/tex', '4.0.0', 'TeX Input');
// Get component root path
const rootPath = MathJax.loader.getRoot();Configure which components to load through the loader configuration.
interface LoaderOptions {
/** Components to load automatically */
load?: string[];
/** Component dependencies */
dependencies?: Record<string, string[]>;
/** Path mappings for component loading */
paths?: Record<string, string>;
/** Source file mappings */
source?: Record<string, string>;
/** Components provided by other components */
provides?: Record<string, string[]>;
}Configuration Examples:
// Basic component loading
MathJax.config.loader = {
load: ['input/tex', '[tex]/ams', 'output/chtml']
};
// Advanced configuration with custom paths
MathJax.config.loader = {
load: ['input/tex', 'output/svg', 'ui/menu'],
paths: {
mathjax: 'https://cdn.jsdelivr.net/npm/mathjax@4',
custom: 'https://my-cdn.com/mathjax-extensions'
},
dependencies: {
'custom/myextension': ['input/tex']
}
};Process different mathematical notation formats.
Core Input Processors:
input/tex - Complete TeX/LaTeX processor with extensionsinput/tex-base - Basic TeX processor without extensionsinput/mml - MathML processorinput/asciimath - AsciiMath processorUsage Examples:
// Load TeX with extensions
MathJax.config.loader.load = ['input/tex'];
// Load basic TeX only
MathJax.config.loader.load = ['input/tex-base'];
// Load multiple input formats
MathJax.config.loader.load = ['input/tex', 'input/mml', 'input/asciimath'];Render mathematics in different formats.
Available Output Processors:
output/chtml - CommonHTML output (HTML/CSS)output/svg - SVG output (Scalable Vector Graphics)Usage Examples:
// Use CommonHTML output
MathJax.config.loader.load = ['input/tex', 'output/chtml'];
// Use SVG output
MathJax.config.loader.load = ['input/tex', 'output/svg'];
// Both outputs available (choose at conversion time)
MathJax.config.loader.load = ['input/tex', 'output/chtml', 'output/svg'];Extend TeX/LaTeX functionality with specialized packages.
Core Extensions:
[tex]/ams - AMS math environments and symbols[tex]/amscd - AMS commutative diagrams[tex]/newcommand - Define custom commands[tex]/color - Color supportMathematical Extensions:
[tex]/boldsymbol - Bold mathematical symbols[tex]/braket - Dirac bra-ket notation[tex]/cancel - Cancel expressions with lines[tex]/enclose - Enclose expressions with boxes/lines[tex]/mhchem - Chemistry notation[tex]/physics - Physics notation and operators[tex]/units - Unit formattingFormatting Extensions:
[tex]/bbox - Bounding boxes and backgrounds[tex]/textmacros - Text formatting commands[tex]/unicode - Unicode character support[tex]/verb - Verbatim text renderingAdvanced Extensions:
[tex]/autoload - Automatic extension loading[tex]/require - Dynamic requirement loading[tex]/configmacros - Configuration-based macrosUsage Examples:
// Load specific extensions
MathJax.config.loader.load = [
'input/tex',
'[tex]/ams',
'[tex]/color',
'[tex]/mhchem',
'output/chtml'
];
// Load many extensions
MathJax.config.loader.load = [
'input/tex',
'[tex]/ams',
'[tex]/amscd',
'[tex]/bbox',
'[tex]/boldsymbol',
'[tex]/braket',
'[tex]/cancel',
'[tex]/color',
'[tex]/enclose',
'[tex]/mhchem',
'[tex]/physics',
'output/svg'
];Enhance mathematical accessibility for assistive technologies.
Available Components:
a11y/semantic-enrich - Semantic analysis and enrichmenta11y/speech - Speech generationa11y/explorer - Interactive explorationa11y/complexity - Mathematical complexity analysisa11y/assistive-mml - Assistive MathML generationa11y/sre - Speech Rule EngineUsage Examples:
// Full accessibility support
MathJax.config.loader.load = [
'input/tex',
'output/chtml',
'a11y/semantic-enrich',
'a11y/speech',
'a11y/explorer',
'a11y/assistive-mml'
];
// Basic accessibility
MathJax.config.loader.load = [
'input/tex',
'output/svg',
'a11y/assistive-mml'
];User interface elements and interactions.
Available Components:
ui/menu - Context menu for mathematical expressionsui/lazy - Lazy loading utilitiesui/safe - Safe mode error handlingUsage Examples:
// Add context menu
MathJax.config.loader.load = [
'input/tex',
'output/chtml',
'ui/menu'
];
// Safe mode with error handling
MathJax.config.loader.load = [
'input/tex',
'output/svg',
'ui/safe'
];DOM adapters for different environments.
Available Adaptors:
adaptors/liteDOM - Lightweight DOM for server-sideadaptors/jsdom - jsdom integrationadaptors/linkedom - LinkedOM integrationUsage Examples:
// Node.js with liteDOM
MathJax.config.loader.load = [
'adaptors/liteDOM',
'input/tex',
'output/svg'
];
// Node.js with jsdom
MathJax.config.loader.load = [
'adaptors/jsdom',
'input/tex',
'output/chtml'
];Ready-to-use combinations for common scenarios.
Available Combinations:
tex-chtml.js - TeX input + CommonHTML outputtex-svg.js - TeX input + SVG outputmml-chtml.js - MathML input + CommonHTML outputmml-svg.js - MathML input + SVG outputNo-Font Variants:
tex-chtml-nofont.js - TeX + CommonHTML without web fontstex-svg-nofont.js - TeX + SVG without web fontsmml-chtml-nofont.js - MathML + CommonHTML without fontsmml-svg-nofont.js - MathML + SVG without fontsSupport multiple input formats simultaneously.
Available Combinations:
tex-mml-chtml.js - TeX + MathML inputs + CommonHTML outputtex-mml-svg.js - TeX + MathML inputs + SVG outputUsage Examples:
<!-- Single format -->
<script src="https://cdn.jsdelivr.net/npm/mathjax@4/tex-chtml.js"></script>
<!-- Multiple formats -->
<script src="https://cdn.jsdelivr.net/npm/mathjax@4/tex-mml-svg.js"></script>
<!-- Without fonts -->
<script src="https://cdn.jsdelivr.net/npm/mathjax@4/tex-svg-nofont.js"></script>Build custom extensions for specialized mathematical notation.
// Define custom extension
const MyCustomExtension = {
name: 'custom',
version: '1.0.0',
// Extension initialization
init(config) {
console.log('Custom extension loaded');
},
// Add custom macros
macros: {
customSymbol: '{\\unicode{x1D4C0}}',
myFunction: ['{\\operatorname{#1}}', 1]
},
// Add custom environments
environments: {
myenvironment: ['\\begin{array}{cc}', '\\end{array}']
}
};
// Register custom extension
MathJax.config.tex = MathJax.config.tex || {};
MathJax.config.tex.packages = MathJax.config.tex.packages || [];
MathJax.config.tex.packages.push('custom');
// Load the extension
MathJax.config.loader.source['[tex]/custom'] = 'path/to/my-extension.js';
MathJax.config.loader.load.push('[tex]/custom');Create input processors for new mathematical formats.
// Custom input processor template
class CustomInputJax {
constructor(config = {}) {
this.config = config;
}
// Process input string
compile(math, doc) {
// Parse custom format
const parsed = this.parse(math.math);
// Convert to internal format
return this.convertToInternal(parsed);
}
parse(input) {
// Custom parsing logic
return { type: 'custom', content: input };
}
convertToInternal(parsed) {
// Convert to MathJax internal format
return this.createMathML(parsed);
}
createMathML(parsed) {
// Generate MathML representation
return '<math><mi>' + parsed.content + '</mi></math>';
}
}
// Register custom input processor
MathJax.startup.registerConstructor('customInput', CustomInputJax);
MathJax.startup.useInput('customInput');Create output processors for new rendering formats.
// Custom output processor template
class CustomOutputJax {
constructor(config = {}) {
this.config = config;
}
// Render mathematics
typeset(math, html) {
const mathML = math.root;
const customHTML = this.renderCustom(mathML);
math.typesetRoot = html.node('span', {
class: 'mjx-custom'
}, [customHTML]);
return math.typesetRoot;
}
renderCustom(mathml) {
// Custom rendering logic
return this.createCustomElement(mathml);
}
createCustomElement(mathml) {
// Generate custom HTML structure
return '<span class="custom-math">' + mathml.textContent + '</span>';
}
styleSheet() {
// Return custom CSS
return `
.mjx-custom {
font-family: 'Custom Math Font';
color: #333;
}
.custom-math {
border: 1px solid #ddd;
padding: 2px 4px;
}
`;
}
}
// Register custom output processor
MathJax.startup.registerConstructor('customOutput', CustomOutputJax);
MathJax.startup.useOutput('customOutput');Load extensions dynamically based on content or user preferences.
// Analyze content to determine needed extensions
function analyzeContent(content) {
const extensions = [];
if (content.includes('\\ce{')) {
extensions.push('[tex]/mhchem');
}
if (content.includes('\\color{')) {
extensions.push('[tex]/color');
}
if (content.includes('\\cancel{')) {
extensions.push('[tex]/cancel');
}
if (content.includes('\\bra{') || content.includes('\\ket{')) {
extensions.push('[tex]/braket');
}
return extensions;
}
// Load extensions dynamically
async function processContentWithExtensions(content) {
const needed = analyzeContent(content);
if (needed.length > 0) {
await MathJax.loader.load(...needed);
}
// Process content
return MathJax.tex2svg(content);
}
// Usage
const chemistry = '\\ce{H2O + CO2 -> H2CO3}';
const result = await processContentWithExtensions(chemistry);Load extensions based on environment or user capabilities.
// Environment-based loading
function loadEnvironmentExtensions() {
const extensions = ['input/tex', 'output/chtml'];
// Add accessibility if screen reader detected
if (hasScreenReader()) {
extensions.push('a11y/semantic-enrich', 'a11y/speech');
}
// Add menu for desktop browsers
if (isDesktop()) {
extensions.push('ui/menu');
}
// Add specific adaptors for Node.js
if (typeof window === 'undefined') {
extensions.push('adaptors/liteDOM');
}
return MathJax.loader.load(...extensions);
}
function hasScreenReader() {
return navigator.userAgent.includes('NVDA') ||
navigator.userAgent.includes('JAWS') ||
window.speechSynthesis;
}
function isDesktop() {
return !('ontouchstart' in window);
}
// Load appropriate extensions
loadEnvironmentExtensions().then(() => {
MathJax.typeset();
});MathJax automatically manages extension dependencies.
// Dependencies are defined in the loader configuration
MathJax.config.loader.dependencies = {
// AMS package requires newcommand
'[tex]/ams': ['input/tex-base', '[tex]/newcommand'],
// Physics requires AMS
'[tex]/physics': ['input/tex-base', '[tex]/ams'],
// Color extensions
'[tex]/colortbl': ['input/tex-base', '[tex]/color'],
// Accessibility dependencies
'a11y/speech': ['a11y/semantic-enrich'],
'a11y/explorer': ['a11y/speech']
};
// When you load an extension, dependencies are loaded automatically
await MathJax.loader.load('[tex]/physics');
// This automatically loads: input/tex-base, [tex]/newcommand, [tex]/amsDefine dependencies for custom extensions.
// Define custom extension dependencies
MathJax.config.loader.dependencies['custom/myextension'] = [
'input/tex-base',
'[tex]/ams',
'[tex]/color'
];
// Register custom extension
MathJax.config.loader.source['custom/myextension'] = '/path/to/my-extension.js';
// Load with automatic dependency resolution
await MathJax.loader.load('custom/myextension');Load only the components you need to minimize bundle size.
// Minimal configuration for basic TeX
MathJax.config.loader.load = [
'input/tex-base', // Basic TeX without extensions
'output/chtml' // Lightweight output
];
// Full-featured configuration
MathJax.config.loader.load = [
'input/tex', // TeX with common extensions
'[tex]/ams', // Mathematical extensions
'[tex]/color', // Color support
'output/svg', // High-quality output
'ui/menu', // User interface
'a11y/assistive-mml' // Basic accessibility
];Use pre-built bundles for common combinations.
// Instead of loading individual components
MathJax.config.loader.load = [
'input/tex',
'[tex]/ams',
'[tex]/newcommand',
'[tex]/textmacros',
'[tex]/noundefined',
'[tex]/require',
'[tex]/autoload',
'[tex]/configmacros',
'output/chtml'
];
// Use pre-built bundle
// <script src="https://cdn.jsdelivr.net/npm/mathjax@4/tex-chtml.js"></script>
// This includes all the above components in a single optimized fileLoad extensions on demand to improve initial page load.
// Core loading
const core = ['input/tex-base', 'output/chtml'];
await MathJax.loader.load(...core);
// Initial render with basic features
MathJax.typeset();
// Load additional features as needed
const loadExtensions = async (extensions) => {
await MathJax.loader.load(...extensions);
MathJax.texReset(); // Reset to recognize new extensions
MathJax.typeset(); // Re-render with new features
};
// Load on user interaction
document.getElementById('load-ams').addEventListener('click', () => {
loadExtensions(['[tex]/ams']);
});
document.getElementById('load-chemistry').addEventListener('click', () => {
loadExtensions(['[tex]/mhchem']);
});