CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-katex

Fast math typesetting for the web.

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

mathtex-script-type.mddocs/

MathTeX Script Type Extension

Automatic script element rendering extension that converts <script type="math/tex"> elements to rendered math, enabling seamless integration with content management systems and legacy HTML.

Import

import "katex/contrib/mathtex-script-type";

For CommonJS:

require("katex/contrib/mathtex-script-type");

Capabilities

Automatic Script Processing

The mathtex-script-type extension automatically processes all <script type="math/tex"> elements in the document body and replaces them with rendered math.

// No explicit API - works automatically once imported
// Processes all script[type*="math/tex"] elements in document.body

Usage Example:

<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" href="katex.css">
  <script src="katex.js"></script>
  <script src="katex/contrib/mathtex-script-type.js"></script>
</head>
<body>
  <!-- Inline math -->
  <script type="math/tex">E = mc^2</script>
  
  <!-- Display math -->
  <script type="math/tex; mode=display">
    \int_0^\infty e^{-x^2} dx = \frac{\sqrt{\pi}}{2}
  </script>
  
  <!-- These will be automatically rendered on page load -->
</body>
</html>

Script Type Recognition

The extension recognizes several script type variations:

<!-- All of these are processed -->
<script type="math/tex">x^2</script>
<script type="math/tex; mode=display">\sum_{i=1}^n i</script>
<script type="Math/Tex">f(x) = x^2</script>
<script type="MATH/TEX; MODE=DISPLAY">\frac{1}{2}</script>

Display Mode Detection

The extension automatically detects display mode from the script type:

// Inline mode (default)
// <script type="math/tex">...</script>
// Renders as: <span class="inline-equation">...</span>

// Display mode  
// <script type="math/tex; mode=display">...</script>
// Renders as: <div class="equation">...</div>

Display Mode Examples:

<!-- Inline math -->
<p>The formula <script type="math/tex">x = \frac{-b \pm \sqrt{b^2-4ac}}{2a}</script> solves quadratic equations.</p>

<!-- Display math -->
<script type="math/tex; mode=display">
\begin{align}
x^2 + y^2 &= r^2 \\
\sin^2 \theta + \cos^2 \theta &= 1
\end{align}
</script>

Error Handling

The extension handles rendering errors gracefully:

<!-- Invalid TeX -->
<script type="math/tex">\invalid{command}</script>
<!-- Results in: original TeX text displayed (not rendered) -->

<!-- Valid TeX -->
<script type="math/tex">\frac{1}{2}</script>  
<!-- Results in: proper math rendering -->

Element Replacement

Script elements are replaced with appropriate containers:

// Inline math replacement:
// <script type="math/tex">x^2</script>
// becomes:
// <span class="inline-equation">[rendered math]</span>

// Display math replacement:
// <script type="math/tex; mode=display">\sum x</script>
// becomes:
// <div class="equation">[rendered math]</div>

CMS Integration

This extension is particularly useful for content management systems that don't allow direct HTML but support script tags:

<!-- WordPress, Drupal, etc. can safely store these -->
<script type="math/tex">
\frac{\partial f}{\partial x} = \lim_{h \to 0} \frac{f(x+h) - f(x)}{h}
</script>

<script type="math/tex; mode=display">
\oint_{\partial \Omega} \mathbf{F} \cdot d\mathbf{l} = \iint_\Omega (\nabla \times \mathbf{F}) \cdot d\mathbf{A}
</script>

Server-Side Generation

Perfect for server-side templates that generate script tags:

<?php
// PHP example
echo '<script type="math/tex">' . htmlspecialchars($latex_formula) . '</script>';
?>
# Python/Django example
def render_math(latex):
    return f'<script type="math/tex">{html.escape(latex)}</script>'
// Node.js example
function mathScript(latex, display = false) {
  const mode = display ? '; mode=display' : '';
  return `<script type="math/tex${mode}">${escapeHtml(latex)}</script>`;
}

Processing Timing

The extension processes scripts immediately upon import:

// All existing script elements are processed
import "katex/contrib/mathtex-script-type";

// For dynamically added content, re-import or process manually
function addMathScript(latex, container, display = false) {
  const script = document.createElement('script');
  script.type = `math/tex${display ? '; mode=display' : ''}`;
  script.textContent = latex;
  container.appendChild(script);
  
  // Re-import to process new script
  import("katex/contrib/mathtex-script-type");
}

Integration with Other Extensions

Works alongside other KaTeX extensions:

<script src="katex.js"></script>
<script src="katex/contrib/mhchem.js"></script>
<script src="katex/contrib/copy-tex.js"></script>
<script src="katex/contrib/mathtex-script-type.js"></script>

<!-- Now supports chemistry in script tags -->
<script type="math/tex; mode=display">
\ce{2H2 + O2 -> 2H2O}
</script>

<!-- And copy-tex works on the rendered output -->

Dynamic Content Handling

For dynamically added content, manually trigger processing:

import katex from "katex";

function processNewMathScripts(container) {
  const scripts = container.querySelectorAll('script[type*="math/tex"]');
  scripts.forEach(script => {
    if (script.processed) return; // Avoid double-processing
    
    const isDisplay = /mode\s*=\s*display/i.test(script.type);
    const element = document.createElement(isDisplay ? 'div' : 'span');
    element.className = isDisplay ? 'equation' : 'inline-equation';
    
    try {
      katex.render(script.textContent, element, { displayMode: isDisplay });
      script.parentNode.replaceChild(element, script);
    } catch (err) {
      element.textContent = script.textContent;
      script.parentNode.replaceChild(element, script);
    }
    
    script.processed = true;
  });
}

// Use with AJAX content
fetch('/api/math-content')
  .then(response => response.text())
  .then(html => {
    const container = document.getElementById('content');
    container.innerHTML = html;
    processNewMathScripts(container);
  });

Legacy System Migration

Ideal for migrating from MathJax script-based systems:

<!-- MathJax-style (also works with this extension) -->
<script type="math/tex">x^2 + y^2 = z^2</script>
<script type="math/tex; mode=display">\sum_{n=1}^\infty \frac{1}{n^2} = \frac{\pi^2}{6}</script>

<!-- No code changes needed for migration -->

Security Considerations

  • Script content is processed as TeX only, no JavaScript execution
  • Safe by design - only mathematical content is rendered
  • XSS protection - TeX parsing prevents script injection
  • Content isolation - script contents are treated as plain text

Browser Compatibility

The extension works in all modern browsers and requires:

  • DOM manipulation APIs (standard since IE9)
  • Query selectors for finding script elements
  • Basic JavaScript for type checking and replacement

Performance Notes

  • Processing occurs once on import/page load
  • Minimal overhead - only processes math/tex script elements
  • Memory efficient - replaces scripts with rendered content
  • Cache friendly - rendered content can be cached like any HTML

Troubleshooting

Scripts not being processed:

  • Ensure script type includes "math/tex" (case insensitive)
  • Verify scripts are in document.body (not head)
  • Check for JavaScript errors preventing extension loading

Math not rendering properly:

  • Validate TeX syntax in script content
  • Ensure KaTeX CSS is loaded
  • Check browser console for specific rendering errors

Display mode not working:

  • Include "mode=display" in script type
  • Verify script type format: type="math/tex; mode=display"
  • Check for typos in mode specification

docs

accessibility.md

advanced-apis.md

auto-rendering.md

chemistry.md

cli.md

configuration.md

copy-tex.md

core-rendering.md

index.md

mathtex-script-type.md

tile.json