Skip to content

Instantly share code, notes, and snippets.

@minocoko
Last active March 27, 2018 15:53
Show Gist options
  • Save minocoko/3193e5e94637e3e496765c32b6123a30 to your computer and use it in GitHub Desktop.
Save minocoko/3193e5e94637e3e496765c32b6123a30 to your computer and use it in GitHub Desktop.
Load font async, only support woff2, woff source
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));
}
}
@minocoko
Copy link
Author

minocoko commented Mar 27, 2018

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')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment