Next.js MathML feature detection + polyfill
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Router from 'next/router'; | |
const namespaceURI = 'http://www.w3.org/1998/Math/MathML'; | |
let supports = false; | |
let inserted = false; | |
function supportsMathML() { | |
const div = document.createElement('div'); | |
div.innerHTML = '<math><mspace height="23px" width="77px" /></math>'; | |
document.body.appendChild(div); | |
const box = div.firstChild.getBoundingClientRect(); | |
document.body.removeChild(div); | |
return Math.abs(box.height - 23) <= 1 && Math.abs(box.width - 77) <= 1; | |
} | |
function pageHasMathElement() { | |
return document.body.getElementsByTagNameNS(namespaceURI, 'math').length; | |
} | |
function insertPolyfill() { | |
const link = document.createElement('link'); | |
link.rel = 'stylesheet'; | |
link.href = '/static/mathPolyfill.css'; // https://fred-wang.github.io/mathml.css/ | |
document.head.appendChild(link); | |
inserted = true; | |
} | |
Router.events.on('routeChangeComplete', () => { | |
if (!window || supports || inserted) { | |
return; | |
} | |
supports = supportsMathML(); | |
if (supports || !pageHasMathElement()) { | |
return; | |
} | |
insertPolyfill(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment