Last active
March 27, 2018 15:53
-
-
Save minocoko/3193e5e94637e3e496765c32b6123a30 to your computer and use it in GitHub Desktop.
Load font async, only support woff2, woff source
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
function load(family, source, descriptors) { | |
if (typeof FontFace.prototype.load === 'function') { | |
return new FontFace(family, source, descriptors) | |
.load() | |
} else { | |
const regex = /url\((.*?)\)(.*\('(.*?)'\))?/ | |
const srcset = source | |
.split(",") | |
.map(src => { | |
const matches = src.match(regex); | |
return { | |
url: matches[1], | |
format: matches[3] || matches[1].substring(matches[1].lastIndexOf(".") + 1) | |
} | |
}) | |
return fetch(srcset.find(src => src.format === 'woff').url) | |
.then(resp => resp.arrayBuffer()) | |
.then(buffer => new FontFace(family, buffer, descriptors)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
usage:
load(family, source, descriptors).then(font => document.fonts.add(font));
source support multi url,
url(xxx.woff2) format('woff2'),url(xxx.woff) format('woff')