Created
December 30, 2018 21:59
-
-
Save hugmanrique/a6fedf0a8862190f713093ddfdc7d5d7 to your computer and use it in GitHub Desktop.
Next.js MathML feature detection + polyfill
This file contains hidden or 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