Last active
August 3, 2020 02:31
-
-
Save panphora/0f220d727999cf27ce62e3fbef7dc306 to your computer and use it in GitHub Desktop.
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
/* | |
ADD EMOJI SUPPORT TO YOUR WEBSITE FOR ALL VISITORS! | |
=================================================== | |
* Many of your visitors probably see � if they don't have emoji support on their device | |
* This script tries to detect if they have emoji support, and, if they don't, it adds it using Twitter's awesome Twemoji library! | |
Instructions | |
------------ | |
* Insert this code before your closing </body> tag | |
*/ | |
// Detect emoji support by drawing the Wizard 🧙♂️ emoji onto a canvas and then seeing if the color of the canvas in that area has changed | |
// Borrowed from Modernizr: https://raw.githubusercontent.com/browserleaks/Modernizr/master/feature-detects/emoji.js | |
function hasEmojiSupport() { | |
var node = window.document.createElement('canvas'); | |
var ctx = node.getContext('2d'); | |
if (!ctx) { | |
return false; | |
} | |
var backingStoreRatio = | |
ctx.webkitBackingStorePixelRatio || | |
ctx.mozBackingStorePixelRatio || | |
ctx.msBackingStorePixelRatio || | |
ctx.oBackingStorePixelRatio || | |
ctx.backingStorePixelRatio || | |
1; | |
var offset = 12 * backingStoreRatio; | |
ctx.fillStyle = '#f00'; | |
ctx.textBaseline = 'top'; | |
ctx.font = '32px Arial'; | |
ctx.fillText('\uD83E\uDDD9\u200D\u2642\uFE0F', 0, 0); // WIZARD | |
var support = ctx.getImageData(offset, offset, 1, 1).data[0] !== 0; | |
return support; | |
}; | |
// if the user doesn't have emoji support, load the Twemoji library | |
if (!hasEmojiSupport()) { | |
var twemojiScriptElem = document.createElement('script'); | |
twemojiScriptElem.src = "https://twemoji.maxcdn.com/v/latest/twemoji.min.js"; | |
var firstScriptElem = document.getElementsByTagName('script')[0]; | |
firstScriptElem.parentNode.insertBefore(twemojiScriptElem, firstScriptElem); | |
twemojiScriptElem.onload = function () { | |
window.twemoji.parse(document.body); | |
// make emoji's display as inline-block elements and align them with the surrounding text | |
firstScriptElem.insertAdjacentHTML("afterend", "img.emoji {display: inline-block;height: 1em;width: 1em;margin: 0 .05em 0 .1em;vertical-align: -0.1em;}"); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment