Coder Social home page Coder Social logo

connect-fonts's Introduction

connect-fonts

Connect/Express font serving middleware. Why? Because Google's font CDN is slow and slow page loads cause users to leave your site.

The middleware looks for requests (expressed in Express terminology):

/:font-list/fonts.css

An example of a match is:

/opensans-regular,opensans-italics/fonts.css

When this route is matched, connect-fonts will generate a CSS response with @font-face declarations that are tailored to the user's browser.

Usage

  1. Include connect-fonts in a node module.
const font_middleware = require("connect-fonts");
  1. Include the font packs that you want to serve.
const opensans = require("connect-fonts-opensans");
  1. Add a middleware by calling the setup function.
    app.use(font_middleware.setup({
      fonts: [ opensans ],
      allow_origin: "https://exampledomain.com",
      ua: "all",
      maxage: 180 * 24 * 60 * 60 * 1000   // 180 days
    }));

fonts - array of font packs. allow_origin - optional - origin to set in the Access-Control-Allow-Origin header. Defaults to undefined. ua - optional - force a user-agent. "all" means serve up all font types to all users. If not specified, the user's user-agent header will be used to send the user only the fonts that their user-agent support. Defaults to all. maxage - optional - provide a max-age in milliseconds for http caching. Defaults to 0. compress - optional - Whether to compress the CSS/font output. Defaults to false.

  1. Add a link tag to include the font CSS. To serve a default, non-locale specific font, include a CSS link that contains the name of the font:
<link href="/opensans-regular/fonts.css" type="text/css" rel="stylesheet"/ >
  1. Set your CSS up to use the new font by using the correct font-family.
    body {
      font-family: 'Open Sans', 'sans-serif', 'serif';
    }

Advanced Usage

Fonts located on another domain (CDN)

It is possible to specify a host where fonts are located. This is useful if font files are located on another domain.

    app.use(font_middleware.setup({
      fonts: [ opensans ],
      host: "https://cdn.exampledomain.com",
      allow_origin: "https://exampledomain.com",
      ua: "all",
      maxage: 180 * 24 * 60 * 60 * 1000   // 180 days
    }));

Locale optimised fonts

If a font pack contains locale optimised fonts, these can be requested by prepending the locale name before the font list in the fonts.css request.

<link href="/en/opensans-regular/fonts.css" type="text/css" rel="stylesheet"/ >

scripts/subset from connect-fonts-tools can be used to create locale-optimised subsets.

Programatically generate CSS for use in build steps

One of the easiest ways to speed up your site is to minimize the number of resources that are requested. The @font-face CSS provided by fonts.css can be fetched programatically and concatinated with other site CSS during a build step.

var fontMiddleware = connect_fonts.setup(...);

// `ua` - user agent. Use 'all' for a CSS bundle that is compatible with all browsers.
// `lang` - language. generate_css can be called once for each served language, or
//            "default" can be specified
// `fonts` - array of font names - e.g. ["opensans-regular", "opensans-italics"]
fontMiddleware.generate_css(ua, lang, fonts, function(err, css) {
  var css_output_path = path.join(output_dir, dep);
  var css_output_dir = path.dirname(css_output_path);

  // create any missing directories.
  mkdirp.sync(css_output_dir);

  // finally, write out the file.
  fs.writeFileSync(css_output_path, css.css, "utf8");
});

Direct access to font files

Once connect fonts setup function is called, a map of URLs=>paths can be retreived using fontMiddleware.urlToPaths. This information can be used in a build step for tools like connect-cachify that need access to the font file to create an caching hash.

Create a Font Pack

A font pack is an npm module like any other node library. Creating a new font pack is similar to creating any npm module.

  1. Install connect-fonts-tools and run its scripts/setup utility.
npm install connect-fonts-tools
cd node_modules/connect-fonts-tools
./scripts/setup
  1. Create a font pack target directory
mkdir <target_path>
  1. Call scripts/create_fontpack from connect-font-tools with the source directory, the target directory, and the pack name.
connect-fonts-tools/scripts/create_fontpack --pn <pack_name> --sp <source_path> --tp <target_path>

If the font pack is for public use, specify the additional parameters to be placed inside the font pack's package.json and README.md files.

connect-fonts-tools/scripts/create_fontpack --pn <pack_name> --ph <pack_homepage_url> --pr <pack_repo_url> --pb <pack_bugtracker_url> --sp <source_path> --tp <target_path>
  1. Check your font pack. script/check_font_pack.js is a basic font pack linter. It will check whether pack configuration is sane and if all expected font files are available. To use it, call check_font_pack.js with the absolute path to the font pack's configuration file.
script/check_font_pack.js ~/development/connect-fonts-opensans/index.js
  1. If the font pack is for public use, publish it to the npm repository
cd <target_path>
npm publish
  1. Install the pack using npm into your project:
npm install <pack_name>

If the font pack is not to be published to the npm repository, it can be installed to another local project directory:

cd <target_project_dir>
npm install <font_pack_directory>

Author:

Get involved:

MOAR font packs! See connect-fonts-tools for tools to make this easy. connect-fonts-opensans is an example of a finished font pack.

Any updates to connect-fonts are appreciated. All submissions will be reviewed and considered for merge.

License:

This software is available under version 2.0 of the MPL:

https://www.mozilla.org/MPL/

connect-fonts's People

Contributors

richardaum avatar vladikoff avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

connect-fonts's Issues

strip out hinting for non-windows platforms

We could make the font-packs a little larger, but reduce client resources a little more, by having separate font files for hinted (Windows) and non-hinted (platforms).

Removing hinting reportedly (don't have the link, sigh) reduces font size considerably--I seem to remember a claim of up to 50%.

Would be super awesome to dynamically remove the hinting, but that's a big step.

font packs should be able to provide own URL-to-path logic

FontAwesome distribution has a very simple structure: just one directory with 5 files.

Unfortunately, we cannot simply say in package.json

"root": <fontawesome-directory>

because we need to play the "locale directory" game. I think this is sometimes impractical. Can we replace cumbersome mapping hashmaps with callback functions that fontpacks can provide?

In the end we just expect a list of fonts, list of files with formats and a mapping

 (font_name, locale, font_format) -> (font_url, font_path)

To work this around http://github.com/kmohrf/connect-fonts-fontawesome needs to copy the files over to match the desired structure.

optionally gzip fonts

Not sure if this is a good idea or not, but wouldn't it be swell to conditionally enable gzipping of fonts?

This would be useful for people not using Nginx/Apache/etc as a front-end proxy, but who still want to compress fonts.

add otf file support

OpenType fonts should be recognized and cheerfully served up in place of TrueType fonts by our beloved connect-fonts.

README typo

README says "Allow-Origin-Access-Control", should be "Access-Control-Allow-Origin" ;-)

package.json file is invalid

Per http://package-json-validator.com/

We should add license information, and it looks like author has a typo (is Author).

{
  "valid": false,
  "errors": [
    "Missing required field: author"
  ],
  "warnings": [
    "Missing recommended field: licenses"
  ],
  "recommendations": [
    "Missing optional field: contributors",
    "Missing optional field: files",
    "Missing optional field: bin",
    "Missing optional field: man",
    "Missing optional field: directories",
    "Missing optional field: config",
    "Missing optional field: bundledDependencies",
    "Missing optional field: optionalDependencies",
    "Missing optional field: engineStrict",
    "Missing optional field: os",
    "Missing optional field: cpu",
    "Missing optional field: preferGlobal",
    "Missing optional field: private",
    "Missing optional field: publishConfig"
  ]
}

Add ability to leave out locale in fonts.css request

Currently, the locale must be specified for every fonts.css request.

If the URL is:

/<list_of_fonts>/fonts.css

Instead:

  • The default font set could be served.
  • The user's headers could be checked for an appropriate locale.

support for other license types

These types of fonts are available at openfontlibrary.org:

  • Apache 2.0
  • Bitstream Vera License (and derivative projects)
  • CC-BY
  • CC-BY-SA
  • Freeware
  • GNU General Public License
  • GNU Lesser General Public License
  • GPL with font exception
  • GUST Font License
  • MIT (X11) License
  • OFL (SIL Open Font License)
    [] Public Domain (not a license)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.