EnglishGuides

CSS: Web­fonts in a lo­cally hos­ted HTML web page

I’ve have cre­a­ted a tool na­med TO­Cjs in as web­page for ge­ne­ra­ting table of con­tents by par­sing an HTML do­cu­ment user pro­vi­des. The tool was de­signed to work lo­cally hos­ted so ne­i­ther the user ne­eds a web­ser­ver to use the tool, nor I need a web­ser­ver to make the tool avai­la­ble for users.


Little bit of self‐advertisement: if you’d like to down­load TO­Cjs, pro­ceed to the Gi­tHub re­po­si­tory here. If you’d like to use it on­line, I host it for that pur­puse on my ser­ver here, too. Ple­ase be aware the on­line ver­sion mi­ght be a few com­mits behind the Git re­po­si­tory if I for­get to pull it on the ser­ver.


Pro­blem

I wan­ted the in­ter­face of the tool to look good so I’ve down­lo­a­ded a web­font, sa­ved it next to my CSS sty­le­sheet and lin­ked the fontname.ttf in the @font-family{}. I be­lieve it wor­ked at first a few mon­ths ago but re­cently I’ve no­ti­ced the web­font lo­ads fine on my web­ser­ver but my Fi­re­fox throws an error in the con­sole when I load it lo­cally on my com­pu­ter:

Cross‐Origin Request Blocked: The Same Ori­gin Po­licy di­sallows rea­ding the re­mote re­source at file:///S:/tools/tocjs/assets/Nunito-Light.ttf. (Re­a­son: CORS request not http).

The is­sue here was that the brow­ser ex­pects CSS to make HTTP calls which it ob­vi­ously does on a ser­ver, but on lo­cal it’s not an HTTP call be­cause the lo­cal com­pu­ter doesn’t have a web­ser­ver. Thus, the brow­ser throws an error about the same ori­gin po­licy be­ing vi­o­la­ted. I’ve go­o­gled around on how to solve it to no avail so I’ve lo­gged a ques­tion to Stac­kO­ver­flow and soon got pretty strai­ght­for­ward an­swer. The an­swer also poin­ted me to ano­ther an­swer on SO which I thou­ght was not re­ally re­le­vant to me at the Go­o­gling time (turns out it was).

So­lu­tion

Con­vert the font to a string in base64 en­co­ding and in­sert it into the CSS. It’ll make the CSS file data size at le­ast the same as the font file data size is, but the brow­ser won’t have to worry about the cross‐origin requests when the page is lo­a­ded lo­cally.

I’ve used OpinionatedGeek’s Base64 En­co­der to con­vert the font file and then I’ve cre­a­ted a se­pa­rate CSS file na­med e.g. font-definition-base64.css de­fi­ning my @font-family like this:

@font-face {
font-family: 'My Font Name';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(data:font/ttf;base64,THE-ENCODED-FONT-STRING) format('truetype');
}

Then, in my main CSS file, I’ve ad­ded a call to the be­gin­ning to load the font-definition-base64.css file:

@import url('font-my-font-name-base64.css')

Af­ter this, the brow­ser lo­ads my font fa­mily per­fectly well even if the HTML file is lo­a­ded in a brow­ser on a lo­cal PC.

Napsat komentář

Vaše emailová adresa nebude zveřejněna. Vyžadované informace jsou označeny *