{"id":26675543,"url":"https://github.com/sakibweb/font-js","last_synced_at":"2025-03-26T03:18:39.494Z","repository":{"id":281492081,"uuid":"945447816","full_name":"sakibweb/Font-JS","owner":"sakibweb","description":"Font loader JS","archived":false,"fork":false,"pushed_at":"2025-03-17T17:41:05.000Z","size":20,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-17T18:43:03.196Z","etag":null,"topics":["easy-font-loader","font-js","font-loader","font-loader-js","import-any-font","load-any-fonts","sakibweb","web-fonts"],"latest_commit_sha":null,"homepage":"http://sakibweb.github.io","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/sakibweb.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2025-03-09T12:57:28.000Z","updated_at":"2025-03-17T17:41:09.000Z","dependencies_parsed_at":null,"dependency_job_id":"8d7cfe0e-1512-439c-8f84-81a988803057","html_url":"https://github.com/sakibweb/Font-JS","commit_stats":null,"previous_names":["sakibweb/font-js"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sakibweb%2FFont-JS","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sakibweb%2FFont-JS/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sakibweb%2FFont-JS/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sakibweb%2FFont-JS/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/sakibweb","download_url":"https://codeload.github.com/sakibweb/Font-JS/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245579731,"owners_count":20638679,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["easy-font-loader","font-js","font-loader","font-loader-js","import-any-font","load-any-fonts","sakibweb","web-fonts"],"created_at":"2025-03-26T03:18:38.875Z","updated_at":"2025-03-26T03:18:39.486Z","avatar_url":"https://github.com/sakibweb.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Font.js: Dynamic Font Loader\n\nEffortlessly load fonts from various providers like Google Fonts, Adobe Fonts, Font Awesome, Bunny Fonts, Fontshare, and even local or custom fonts with a simple and consistent JavaScript class.\n\n## Features\n\n*   **Provider Agnostic:** Supports multiple font providers including Google Fonts, Adobe Fonts (Typekit), Font Awesome, Bunny Fonts, Fontshare, Local Fonts, and Custom/Self-hosted fonts.\n*   **Automatic Provider Detection:**  Intelligently detects the font provider based on your configuration, or you can explicitly specify it.\n*   **Promise-Based Loading:** Uses Promises for asynchronous font loading, allowing you to easily handle success and error scenarios.\n*   **Flexible Configuration:**  Offers a wide range of configuration options tailored to each font provider, covering font families, weights, styles, subsets, project IDs, CDN URLs, and more.\n*   **CSS Injection:**  Dynamically injects the necessary CSS into the `\u003chead\u003e` of your document to load the fonts.\n*   **Font Class Application (Optional):**  Automatically applies a CSS class to your elements to use the loaded font, making integration seamless.\n*   **Local and Custom Font Support:**  Load fonts directly from your local server or specify custom CSS for self-hosted fonts.\n*   **Error Handling:**  Provides clear error messages when font loading fails or configuration is incorrect.\n\n## Installation\n\nTo use Font.js, simply include the code in your JavaScript project. You can copy and paste the entire `Font` class code directly into your script or create a separate `Font.js` file and include it in your HTML:\n\n```html\n\u003cscript src=\"Font.js\"\u003e\u003c/script\u003e\n\u003cscript\u003e\n  // Your font loading code here\n\u003c/script\u003e\n```\n### CDN\n```html\n\u003cscript src=\"https://cdn.jsdelivr.net/gh/sakibweb/Font-JS@main/Font.min.js\"\u003e\u003c/script\u003e\n```\n\n\nAlternatively, if you are using a module bundler (like Webpack or Parcel), you can save the code as `Font.js` and import it:\n\n```javascript\nimport Font from './Font.js'; // Or the path to your Font.js file\n\n// Your font loading code here\n```\n\n## Usage\n\nUsing the `Font` class is straightforward. Create a new `Font` instance with the desired provider name (optional, if it can be detected) and a configuration object specific to the provider. Then, call the `load()` method to initiate font loading.\n\nHere are examples for each supported font provider:\n\n### Google Fonts\n\n```javascript\nconst googleFont = new Font('google', {\n  name: 'Roboto', // or family: 'Roboto'\n  weights: [400, 700], // or weight: 400, or weights: '400;700'\n  subsets: ['latin', 'cyrillic'], // or subset: 'latin'\n  display: 'swap', // Optional: 'auto', 'block', 'fallback', 'optional', 'swap'\n  use: '.my-text-class' // Optional: CSS class to apply the font to\n});\n\ngoogleFont.load()\n  .then(() =\u003e console.log('Google Font loaded successfully!'))\n  .catch(error =\u003e console.error('Failed to load Google Font:', error));\n```\n\n**Configuration Options for Google Fonts:**\n\n*   `name` or `family`: (Required) The name of the Google Font family (e.g., 'Roboto', 'Open Sans'). Use either `name` or `family`.\n*   `weights` or `weight`: (Optional) Font weights to load. Can be a string, number, or an array of strings/numbers. Examples: `'400'`, `400`, `[400, 700]`, `'400;700'`. Defaults to `400`.\n*   `styles` or `style`: (Optional) Font styles to load. Can be a string or an array of strings. Examples: `'italic'`, `['normal', 'italic']`. Defaults to `normal`.  *(Note: For Google Fonts, styles are often implicitly handled by weights, so you may not need to explicitly specify styles in many cases.)*\n*   `subsets` or `subset`: (Optional) Font subsets to load (e.g., 'latin', 'cyrillic', 'vietnamese'). Can be a string or an array of strings.\n*   `display`: (Optional)  Defines how font files are downloaded and used by the browser. Options: `'auto'`, `'block'`, `'fallback'`, `'optional'`, `'swap'`. Defaults to `'swap'` for better performance.\n*   `use`: (Optional) CSS class selector (e.g., `.my-text-class`, `#my-element`) to apply the loaded font to. This will create a CSS rule setting `font-family`, `font-weight`, `font-style`, and `font-display` for the specified class.\n\n### Adobe Fonts (Typekit)\n\n```javascript\nconst adobeFont = new Font('adobe', {\n  projectId: 'your-adobe-project-id' // or kitId: 'your-adobe-kit-id'\n  // use: '.my-adobe-text' // Optional: CSS class to apply the font\n});\n\nadobeFont.load()\n  .then(() =\u003e console.log('Adobe Font loaded successfully!'))\n  .catch(error =\u003e console.error('Failed to load Adobe Font:', error));\n```\n\n**Configuration Options for Adobe Fonts:**\n\n*   `projectId` or `kitId`: (Required) Your Adobe Fonts Project ID or Kit ID. Use either `projectId` or `kitId`.\n*   `use`: (Optional) CSS class selector to apply the font.\n\n### Font Awesome\n\n```javascript\nconst fontAwesome = new Font('font_awesome', {\n  version: '6.5.1' // Optional: Specify Font Awesome version. Defaults to latest 6.x.\n  // url: 'path/to/your/font-awesome.css' // Optional: Use a custom Font Awesome CSS URL\n  // use: '.fa-icons' // Optional: CSS class to apply Font Awesome styles\n});\n\nfontAwesome.load()\n  .then(() =\u003e console.log('Font Awesome loaded successfully!'))\n  .catch(error =\u003e console.error('Failed to load Font Awesome:', error));\n```\n\n**Configuration Options for Font Awesome:**\n\n*   `version`: (Optional) Specify the Font Awesome version to load from CDNjs. Defaults to the latest 6.x version (`6.5.1` at the time of writing).\n*   `url`: (Optional)  Provide a custom URL to your Font Awesome CSS file. If provided, `version` is ignored.\n*   `use`: (Optional) CSS class selector to apply Font Awesome styles (though Font Awesome usually applies styles globally).\n\n### Bunny Fonts\n\n```javascript\nconst bunnyFont = new Font('bunny', {\n  family: 'Nunito', // or bunnyFontFamily: 'Nunito'\n  variants: ['400', '700', 'italic'], // or variant: '400', or weights: '400;700'\n  subsets: ['latin', 'cyrillic'], // or subset: 'latin'\n  format: 'css2', // Optional: 'css2' (default), 'woff2' (direct download link)\n  use: '.bunny-text' // Optional: CSS class to apply the font\n});\n\nbunnyFont.load()\n  .then(() =\u003e console.log('Bunny Font loaded successfully!'))\n  .catch(error =\u003e console.error('Failed to load Bunny Font:', error));\n```\n\n**Configuration Options for Bunny Fonts:**\n\n*   `family` or `bunnyFontFamily`: (Required) The font family name from Bunny Fonts (e.g., 'Nunito', 'Open Sans'). Use either `family` or `bunnyFontFamily`.\n*   `variants` or `weights` or `variant`: (Optional) Font variants or weights. Can be a string, array, or number. Examples: `'400'`, `400`, `['400', '700']`, `'400,700'`, `'italic'`.\n*   `subsets` or `subset`: (Optional) Font subsets to load (e.g., 'latin', 'cyrillic'). Can be a string or an array of strings.\n*   `format`: (Optional)  Font format to request. `'css2'` (default, loads CSS file) or `'woff2'` (returns direct download link - *currently loads CSS even with 'woff2'*).\n*   `use`: (Optional) CSS class selector to apply the font.\n\n### Fontshare\n\n```javascript\nconst fontshareFont = new Font('fontshare', {\n  fontshareId: 'your-fontshare-id' // or id: 'your-fontshare-id'\n  // use: '.fontshare-text' // Optional: CSS class to apply the font\n});\n\nfontshareFont.load()\n  .then(() =\u003e console.log('Fontshare Font loaded successfully!'))\n  .catch(error =\u003e console.error('Failed to load Fontshare Font:', error));\n```\n\n**Configuration Options for Fontshare:**\n\n*   `fontshareId` or `id`: (Required) Your Fontshare Font ID. Use either `fontshareId` or `id`.\n*   `use`: (Optional) CSS class selector to apply the font.\n\n### Local Fonts\n\n```javascript\nconst localFont = new Font('local', {\n  localFontName: 'MyCustomFont', // or name: 'MyCustomFont' - The name you will use in CSS\n  localSrc: 'url(/fonts/MyCustomFont.woff2) format(\"woff2\")', // or src: 'url(/fonts/MyCustomFont.woff2) format(\"woff2\")' - Path to your font file(s)\n  weight: 700, // Optional: Font weight\n  style: 'italic', // Optional: Font style\n  display: 'fallback', // Optional: font-display property\n  // use: '.local-text' // Optional: CSS class to apply the font\n});\n\nlocalFont.load()\n  .then(() =\u003e console.log('Local Font loaded successfully!'))\n  .catch(error =\u003e console.error('Failed to load Local Font:', error));\n```\n\n**Configuration Options for Local Fonts:**\n\n*   `localFontName` or `name`: (Required) The font family name you will use in your CSS rules (e.g., 'MyCustomFont'). Use either `localFontName` or `name`.\n*   `localSrc` or `src`: (Required) The `@font-face src` value, including the URL to your font file and format hints. Example: `'url(/fonts/MyFont.woff2) format(\"woff2\"), url(/fonts/MyFont.woff) format(\"woff\")'`. Use either `localSrc` or `src`.\n*   `weight` or `fontWeight`: (Optional) Font weight.\n*   `style` or `fontStyle`: (Optional) Font style.\n*   `display`: (Optional) `font-display` property. Defaults to `swap`.\n*   Other `@font-face` properties (Optional): You can include any other valid `@font-face` properties directly in the `fontConfig` object (e.g., `unicode-range`, `font-stretch`).\n*   `use`: (Optional) CSS class selector to apply the font.\n\n### Custom/Self-Hosted Fonts\n\nYou can load custom fonts using three methods: providing a CSS URL, providing raw CSS rules, or defining `@font-face` properties directly.\n\n**1. Loading via CSS URL:**\n\n```javascript\nconst customFontByURL = new Font('custom', {\n  url: '/css/my-custom-font.css' // URL to your CSS file containing @font-face rules\n  // use: '.custom-text-url' // Optional: CSS class to apply the font\n});\n\ncustomFontByURL.load()\n  .then(() =\u003e console.log('Custom Font (URL) loaded successfully!'))\n  .catch(error =\u003e console.error('Failed to load Custom Font (URL):', error));\n```\n\n**Configuration Options (CSS URL):**\n\n*   `url`: (Required) URL to a CSS file that contains the `@font-face` rules for your custom font.\n*   `use`: (Optional) CSS class selector to apply the font.\n\n**2. Loading via Raw CSS Rules:**\n\n```javascript\nconst customFontByCSS = new Font('custom', {\n  css: `@font-face {\n      font-family: 'MySelfHostedFont';\n      src: url('/fonts/MySelfHostedFont.woff2') format('woff2');\n      font-weight: 400;\n      font-style: normal;\n      font-display: swap;\n    }`\n  // use: '.custom-text-css' // Optional: CSS class to apply the font\n});\n\ncustomFontByCSS.load()\n  .then(() =\u003e console.log('Custom Font (CSS) loaded successfully!'))\n  .catch(error =\u003e console.error('Failed to load Custom Font (CSS):', error));\n```\n\n**Configuration Options (Raw CSS):**\n\n*   `css`: (Required) A string containing the raw CSS rules, typically including `@font-face` declaration(s).\n*   `use`: (Optional) CSS class selector to apply the font.\n\n**3. Loading via `@font-face` Properties:**\n\n```javascript\nconst customFontByProps = new Font('custom', {\n  name: 'MySelfHostedFont', // Required: Font family name\n  src: '/fonts/MySelfHostedFont.woff2', // Required: URL to the font file\n  weight: 400, // Optional: Font weight\n  style: 'normal', // Optional: Font style\n  display: 'swap', // Optional: font-display\n  // use: '.custom-text-props' // Optional: CSS class to apply the font\n});\n\ncustomFontByProps.load()\n  .then(() =\u003e console.log('Custom Font (Properties) loaded successfully!'))\n  .catch(error =\u003e console.error('Failed to load Custom Font (Properties):', error));\n```\n\n**Configuration Options (`@font-face` Properties):**\n\n*   `name`: (Required) Font family name for the `@font-face` rule.\n*   `src`: (Required) URL to the font file.\n*   `weight` or `fontWeight`: (Optional) Font weight.\n*   `style` or `fontStyle`: (Optional) Font style.\n*   `display`: (Optional) `font-display` property. Defaults to `swap`.\n*   Other `@font-face` properties (Optional): You can include any other valid `@font-face` properties directly in the `fontConfig` object (e.g., `unicode-range`, `font-stretch`).\n*   `use`: (Optional) CSS class selector to apply the font.\n\n## API Reference\n\n### `constructor(providerName?, fontConfig)`\n\n*   **`providerName` (optional):**  A string specifying the font provider. If not provided, the class attempts to detect the provider based on the `fontConfig`. Supported provider names (case-insensitive) and their aliases are:\n    *   `google`, `go`, `g`\n    *   `adobe`, `ad`, `a`, `typekit`, `type`, `kit`, `ty`, `tk`\n    *   `font_awesome`, `font`, `wesome`, `fo`, `we`, `fw`\n    *   `bunny`, `bun`, `bu`\n    *   `fontshare`, `sh`, `fs`\n    *   `local`, `lo`\n    *   `custom`, `selfhosted`\n*   **`fontConfig` (required):** An object containing configuration options specific to the chosen font provider. See the \"Usage\" section for details on configuration options for each provider.\n\n### `load()`\n\n*   Returns a `Promise` that resolves when the font is loaded successfully and rejects if there's an error during loading.\n\n## Error Handling\n\nThe `load()` method returns a Promise that will reject if:\n\n*   The specified `providerName` is not supported or cannot be detected.\n*   Required configuration options for a provider are missing (e.g., font name for Google Fonts, project ID for Adobe Fonts).\n*   There is an error loading the CSS file from a URL or injecting CSS rules.\n\nYou can use `.catch()` on the Promise returned by `load()` to handle errors and display user-friendly messages or implement fallback strategies.\n\n## Applying Font Classes (`use` option)\n\nThe optional `use` configuration parameter allows you to automatically apply the loaded font to specific elements by creating and injecting a CSS class.\n\nFor example, if you set `use: '.my-text-class'` in your font configuration, the Font.js class will:\n\n1.  Load the font.\n2.  Create a CSS rule like:\n\n    ```css\n    .my-text-class {\n      font-family: \"Font Name\", sans-serif; /* Font Name will be replaced with the actual font name */\n      /* ... other font properties if configured (weight, style, display) ... */\n    }\n    ```\n\n3.  Inject this CSS rule into the `\u003chead\u003e` of your document.\n\nNow, you can simply add the class `my-text-class` to any HTML element to apply the loaded font.\n\n**Important Notes about `use`:**\n\n*   The `use` option creates a new `\u003cstyle\u003e` tag in the `\u003chead\u003e` with an ID based on the class name to avoid duplication if you load the same font multiple times with the same `use` class.\n*   It sets `font-family`, and optionally `font-weight`, `font-style`, and `font-display` in the generated CSS rule based on your font configuration.\n*   If you provide a class name starting with `.`, it will create a class-based CSS rule. If you provide a class name without `.`, it will add that class directly to the `\u003chtml\u003e` element's `classList`.\n\n## Contributing\n\nContributions are welcome! If you find bugs, have feature requests, or want to improve the code, please feel free to open issues or submit pull requests on [the repository link](https://github.com/sakibweb/Font-JS).\n\n## License\n\n[MIT License](https://github.com/sakibweb/Font-JS/blob/main/LICENSE)\n\n---\n\nThis README provides comprehensive documentation for using the `Font.js` class. You can copy and paste this content into a `README.md` file in your project. Remember to replace placeholders like `your-adobe-project-id`, `your-fontshare-id`, font file paths, and the license information with your actual details.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsakibweb%2Ffont-js","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsakibweb%2Ffont-js","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsakibweb%2Ffont-js/lists"}