Problem / Motivation
The current MathJax module loads the MathJax library globally on all pages where it is enabled,
regardless of whether mathematical notation is actually present on the page.
On educational, documentation, and publishing sites, this leads to unnecessary JavaScript payload,
avoidable performance degradation, and negative impact on Core Web Vitals (notably LCP and INP)
for pages that do not contain math content.
Additionally, site builders currently have no supported way to:
- Select between MathJax v2 and MathJax v3
- Conditionally load MathJax based on content type or route
- Opt into async or deferred loading strategies
Proposed solution
Introduce an optional submodule (working title: MathJax Advanced Loader)
that extends the existing MathJax module without changing its default behavior.
The submodule would provide opt-in configuration for:
-
MathJax version selection:
- MathJax v2 (legacy / default)
- MathJax v3 (opt-in)
- Custom CDN URL
-
Conditional loading strategies (mutually exclusive):
- Load only on selected content types
- Load only on matching route patterns
- Optional experimental auto-detection of math delimiters in rendered content
- Optional async / defer loading, explicitly enabled by administrators
All features would be disabled by default. Sites not enabling the submodule would experience
no behavior changes.
Scope and compatibility
- No changes to existing MathJax defaults
- No modification of rendered content
- No user-agent or crawler-specific behavior
- Compatible with render caching and Dynamic Page Cache
The implementation would attach MathJax libraries conditionally using
hook_page_attachments_alter(), following established Drupal patterns.
Next steps
If the approach is acceptable, I am happy to:
- Create a sandbox implementation
- Submit an initial patch for review
- Adjust scope based on maintainer feedback
Issue fork mathjax-3564855
Show commands
Start within a Git clone of the project using the version control instructions.
Or, if you do not have SSH keys set up on git.drupalcode.org:
- 3564855-async
changes, plain diff MR !9
- 3564855-proposal-optional-mathjax
compare
Comments
Comment #2
cilefen commentedA site can use separate text formats, which only loads the library if an applicable text filter is active.
There are too many suggestions in this issue to be done at one time, and some ideas duplicate those in existing issues.
Comment #3
cilefen commentedWhat are the reasons to implement these changes as a sub module?
Comment #6
cilefen commented@akash2824, it has been four months with no reply from you. I opened a small merge request to load the main library asynchronously.
Comment #7
cilefen commented