Skip to content

Instantly share code, notes, and snippets.

@arielsalminen
Last active August 28, 2020 06:07
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save arielsalminen/c4016ff88745a0846b94 to your computer and use it in GitHub Desktop.
Save arielsalminen/c4016ff88745a0846b94 to your computer and use it in GitHub Desktop.
Convert Google WOFF font to base64 format and inline to <head> of document
// Get binary file using XMLHttpRequest
function getBinary(file) {
var xhr = new XMLHttpRequest();
xhr.open("GET", file, false);
xhr.overrideMimeType("text/plain; charset=x-user-defined");
xhr.send(null);
return xhr.responseText;
}
// Base64 encode binary string
// Stolen from http://stackoverflow.com/questions/7370943/retrieving-binary-file-content-using-javascript-base64-encode-it-and-reverse-de
function base64Encode(str) {
var CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var out = "", i = 0, len = str.length, c1, c2, c3;
while (i < len) {
c1 = str.charCodeAt(i++) & 0xff;
if (i == len) {
out += CHARS.charAt(c1 >> 2);
out += CHARS.charAt((c1 & 0x3) << 4);
out += "==";
break;
}
c2 = str.charCodeAt(i++);
if (i == len) {
out += CHARS.charAt(c1 >> 2);
out += CHARS.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));
out += CHARS.charAt((c2 & 0xF) << 2);
out += "=";
break;
}
c3 = str.charCodeAt(i++);
out += CHARS.charAt(c1 >> 2);
out += CHARS.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
out += CHARS.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
out += CHARS.charAt(c3 & 0x3F);
}
return out;
}
// When menu is clicked, load font file, encode it and inline to the doc <head>
document.querySelector("button").addEventListener("click", function() {
var base64EncodedFont = base64Encode(getBinary("http://fonts.gstatic.com/s/shadowsintolight/v6/clhLqOv7MXn459PTh0gXYMdQSYiIg2Yb25Hg13-ek1M.woff"));
var fontCode = "@font-face { font-family: 'viljamis'; src: url('data:application/font-woff;base64," + base64EncodedFont + "') format('woff'); font-style: normal; font-weight: normal }";
var styleElement = document.createElement("style");
styleElement.type = "text/css";
if (styleElement.styleSheet) {
styleElement.styleSheet.cssText = fontCode;
} else {
styleElement.innerHTML = fontCode;
}
document.head.appendChild(styleElement);
// Finally set the new font-family to some element
element.style.fontFamily = "'viljamis', sans-serif";
}, false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment