问题
I'm trying to create an assets loader based on XMLHttpRequest only. I'm loading images with the help of XMLHttpRequest, getting it's responce of "blob" type and converting it to a normal html element. Something like this:
var request = new XMLHttpRequest();
var image;
var blob;
request.onreadystatechange= function() {
if (request.readyState === 4) {
if (request.status === 200) {
blob = request.response;
image = new Image();
image.src = window.URL.createObjectURL(blob);
}
}
};
request.responseType = 'blob';
request.open("GET", "resource_url", true);
request.send();
I want to implement the same conception for loading fonts and registering them on the page after loaded. It it posible in general? What should I do with blob responce after it is received?
回答1:
For starters you'll need to switch to CSS for this, as that's the only way of loading fonts into a page currently (the Font Loading API is on its way, but has almost zero support right now).
In CSS, custom font declaration looks something like this:
@font-face {
font-family: "Yo Font";
src: url(data:application/x-font-woff;charset=utf-8;base64,d09GRgABAA...) format("woff");
font-weight: normal;
font-style: normal;
}
How exactly your font-face
declaration looks depends on the type of fonts you're loading. More info in the MDN CSS spec for font-face here.
This means that you'll have to create a stylesheet dynamically, using it to load your fonts. You have two methods for updating the stylesheet.
- Dynamically updating the rules of the stylesheet via the StyleSheet DOM API (most efficient method), you'd get your
StyleSheet
object withstyleElement.stylesheet
- Appending your
font-face
declarations to theinnerHTML
of a<style />
element.
来源:https://stackoverflow.com/questions/34922932/javascript-create-font-from-blob-data