Skip to content

Instantly share code, notes, and snippets.

@hugmanrique
Created December 30, 2018 21:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hugmanrique/a6fedf0a8862190f713093ddfdc7d5d7 to your computer and use it in GitHub Desktop.
Save hugmanrique/a6fedf0a8862190f713093ddfdc7d5d7 to your computer and use it in GitHub Desktop.
Next.js MathML feature detection + polyfill
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