Reputation: 10148
I have a problem with JavaScript FileReader and/or CSS @font-face (or it could possibly be a HTML DOM issue - not sure).
I'm dragging a font file from desktop and dropping it into browser's window with a little help from HTML5 drag&drop, then receiving File object and trying to handle it.
Here's the JavaScript code which does this:
//getting the File object
var file = e.dataTransfer.files[0];
var reader = new FileReader();
reader.onload = function(event) {
var contents = event.target.result;
//most important thing here - appending style into HEAD (jQuery)
$('head').append('<style type="text/css">@font-face { font-family:"myFont";
src: url("'+contents+'"); }</style>');
};
reader.onerror = function(event) {
console.error("File could not be read! Code " + event.target.error.code);
};
//read file
reader.readAsDataURL(file);
Final CSS appended to head look's like this:
<style type="text/css">
@font-face {
font-family: "myFont";
src: url("data:;base64;Ahs5hD3..."); // here come's the URL of 'cached' font. A lots of letters and digits
}
</style>
The CSS itself is appending without any problem. The problem is that the font-family isn't applied. After the whole magic I use Firebug (or it's Chrome equivalent) to set font-family of some elements to "myFont" but it applies default font (Times new roman I guess).
I know I can upload the font to achieve this (with PHP e.g.) but that's not the point.
Possible question here might be:
1. Is it possible to append CSS style on the fly and use it without reloading (probably TRUE if it is possible with firebug)?
2. Is it possible to use a font file from a not yet uploaded(local?) resource like that returned by javascript getAsDataUrl function (TRUE - it is possible with an image file)?
So, both things are possible in some circumstances, then what do I do wrong? (maybe file MIME type? Notice that in @font-face src parameter "data:" part is empty)
Upvotes: 8
Views: 2058
Reputation: 31
I don't have the time right now, to try it out, but as I've read your code, the issue may/should be, that you don't support a mime time in your data uri:
src: url("data:;base64;Ahs5hD3..."
A rather "agressive" counter-example:
src: url(data:application/x-font-woff;charset=utf-8;base64,d09GRg
I'll get back to trying it out and digging into it.
Upvotes: 1