Is there a way to use JavaScript to import several custom fonts at once?

Is there a way to import a long list of custom fonts as icons using Javascript? I have been obtaining the font list from an API, but importing them one by one with pure CSS using @font-face is time-consuming and difficult to maintain.

@font-face {
    font-family: 'Animal-1';
    src:  url('http://ggt-des.ibge.gov.br/styles/fontes/Animal-1.ttf');
    font-weight: normal;
    font-style: normal;
};

Font List:

{"Animais-1.ttf": "http://ggt-des.br/styles/fontes/Animais-1.ttf",
"Animais-2.ttf": "http://ggt-des.br/styles/fontes/Animais-2.ttf",
"Animais.ttf": "http://ggt-des.br/styles/fontes/Animais.ttf",
"CPRM_Fontes.ttf": "http://ggt-des.br/styles/fontes/CPRM_Fontes.ttf",
"ESRI-Electric.ttf": "http://ggt-des.br/styles/fontes/ESRI-AMFM-Electric.ttf",
"ESRI-AMFM-Gas.ttf": "http://ggt-des.br/styles/fontes/ESRI-AMFM-Gas.ttf"}

Answer №1

If you want to add a style element to the head using JavaScript, you can follow the code snippet below.

DEMO

let head = document.head || document.getElementsByTagName('head')[0],
  style = document.createElement('style'),
  fonts = {
    "Animais-1.ttf": "http://ggt-des.br/styles/fontes/Animais-1.ttf",
    "Animais-2.ttf": "http://ggt-des.br/styles/fontes/Animais-2.ttf",
    "Animais.ttf": "http://ggt-des.br/styles/fontes/Animais.ttf",
    "CPRM_Fontes.ttf": "http://ggt-des.br/styles/fontes/CPRM_Fontes.ttf",
    "ESRI-Electric.ttf": "http://ggt-des.br/styles/fontes/ESRI-AMFM-Electric.ttf",
    "ESRI-AMFM-Gas.ttf": "http://ggt-des.br/styles/fontes/ESRI-AMFM-Gas.ttf"
  };

head.appendChild(style);

style.type = 'text/css';

let css = Object.entries(fonts).map(v => `@font-face {
    font-family: "${v[0].split('.')[0]}";
    src:  url(${v[1]});
    font-weight: normal;
    font-style: normal;
}`).join('');

if (style.styleSheet) {
  // This is required for IE8 and below.
  style.styleSheet.cssText = css;
} else {
  style.appendChild(document.createTextNode(css));
}
.one {
  font-family: "Animais-1";
}

.two {
  font-family: "Animais-2";
}

.three {
  font-family: "Animais";
}

.four {
  font-family: "CPRM_Fontes";
}

.five {
  font-family: "ESRI-Electric";
}

.six {
  font-family: "ESRI-AMFM-Gas";
}
<div class="one">1</div>
<div class="two">2</div>
<div class="three">3</div>
<div class="four">4</div>
<div class="five">5</div>
<div class="six">6</div>


Alternatively, you can utilize a mixin in SASS by creating a .scss file instead of .css.

  1. In the .scss file, define an @mixin, which functions similarly to a function.

  2. Then, use the mixin with @include while passing parameters, similar to calling a function.

MIXIN example

@mixin font-face($name, $path, $weight: null, $style: null){
    @font-face {
        font-family: quote($name);
        font-style: $style;
        font-weight: $weight;
        src: $path;
    }
}
@include font-face("Animais-2", "http://ggt-des.br/styles/fontes/Animais-1.ttf", 'normal', 'normal');
@include font-face("Animais-2", "http://ggt-des.br/styles/fontes/Animais-2.ttf", 'normal', 'normal');
@include font-face("Animais", "http://ggt-des.br/styles/fontes/Animais.ttf", 'normal', normal);
@include font-face("CPRM_Fontes", "http://ggt-des.br/styles/fontes/CPRM_Fontes.ttf", 'normal', 'normal');
@include font-face("ESRI-Electric", "http://ggt-des.br/styles/fontes/ESRI-Electric.ttf", 'normal', 'normal');
@include font-face("ESRI-AMFM-Gas", "http://ggt-des.br/styles/fontes/ESRI-AMFM-Gas.ttf", 'normal', 'normal');

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I make multiple elements change color when hovering with CSS?

Hey there! I have a little design challenge that I need help with. On my website (), I am trying to make multiple elements of a specific item change color when the user hovers over the text. If you hover over the "more" menu item, you'll notice that o ...

Tips for visually conveying the values of x and y using SVG symbols

I recently came across a blog post discussing the use of SVG symbols for icons, which inspired me to create representations of symbols using svg files. The original svgs I used had properties like x, y, height and width. However, when I tried adding these ...

approach for extracting values from nested objects using specified key

There are objects in my possession that contain various nested objects: let obj = { nestedObject: { key: value } } or let obj2 = { nestedObject2: { nestedObject3: { key2: value2 } } } and so on. Retrieving the values from these objects i ...

"Troubleshooting issues with Material Design components in AngularJS: Why is <md-select> not functioning correctly

I'm attempting to implement the <md-select> tag, but I can't seem to achieve the same result as shown here. This is the code I've written: <div layout="column" layout-align="center center" style="margin: 0px 10px 0px 5px;"> & ...

The coloring feature in Excel Add-in's React component fails to populate cells after the "await" statement

Currently, I am developing a Microsoft Excel Add-in using React. My goal is to assign colors to specific cells based on the value in each cell, indicated by a color code (refer to the Board Color column in the image below). To achieve this, I retrieve the ...

I am constantly encountering this issue: Uncaught TypeError - It's impossible to read properties of undefined (specifically 'image') in PromptCard at PromptCard.jsx on line 37

Click here to see the error message This is the code for my components\PromptCard.jsx file: "use client"; import { useState } from "react"; import Image from "next/image"; import { useSession } from "next-auth/reac ...

The $routeChangeSuccess event is failing to trigger in ngNewRouter in AngularJS version 1.4

Transitioning from AngularJS 1.3 to AngularJS 1.4 has brought about some changes, including the use of AngularJS's new route method known as ngNewRouter, specifically introduced in AngularJS 1.4. Below is a snippet of my code: var versionModule = ng ...

Bars of varying heights (Google Chart)

I have incorporated a Google chart within a mat-grid-tile. In this setup, one column displays a value of 50, while the other showcases a value of 30. These particular values are sourced from myService and are accurate. Although when I hover over the bars i ...

Prioritize moving the JavaScript onload handler to the end of the queue

I am looking to include a JavaScript file at the very end of footer.php using a WordPress plugin. I attempted to do this with the 'add_action' Hook, but found that it is adding the JavaScript code near the </body> tag. add_action('wp_ ...

Issue with nextjs not returning the updated object correctly

I'm currently developing a nextjs app that incorporates authentication. There are two key functions that I execute on each page load. The first function checks for the existence of jwt cookies and then calls another function to validate the tokens if ...

Saving data from the Viewbag into a jQuery array or object on the client side

Imagine this scenario: I have a dynamic object called ViewBag, which is essentially a list filled with some results; Scenario 1: User 1 enters and populates the ViewBag.Products object with a list of 50 items; Scenario 2: User 2 enters and fills t ...

Can the html content provided by the user be extracted and highlighted?

When utilizing the onClick function in ReactJS, I am receiving the entire property which includes Lorem Ipsum is simply dummy text. However, I only require the highlighted content like "is simply dummy". Is there a way to achieve this?</p> ...

The jQuery UI Sortable functions are being triggered at lightning speed

I am currently working on a project where users can create a seating chart, add rows and tables, and move the tables between different rows. The functionality for adding rows and moving tables already exists in the code. However, I am facing an issue where ...

Why does the getComputedStyle function return null for IE11 and Edge when using Kendo React Grid within a Popout window, while it works fine in Chrome, Opera, and Firefox?

Check out my stackblitz demo where I am experimenting with rendering a Kendo React Grid inside a popout window using the react-popout-component. The demo runs smoothly in Chrome, Opera, and Firefox, but encounters issues in Edge and IE11 due to a null valu ...

Protractor issue: Out of bounds error encountered when attempting to use a function for the second time

I encountered an issue with a function that selects a category from a list of available categories. The function worked perfectly in my initial test, but when I used it with a different valid category name for another test, it failed and displayed the foll ...

What is the best way to retrieve an image URL from a CSS file located in a public folder within a

Trying to set a background image in a css file located inside the public/ folder of Rails, but want the image to be sourced from the app/assets/images/ directory. Currently using the code below: background: url("bg-noise.png"); This method typically work ...

Incorporate an icon into an Angular Material input field

I want to enhance my input search bar by adding a search icon from Angular Material : <aside class="main-sidebar"> <section class="sidebar control-sidebar-dark" id="leftMenu"> <div> <md-tabs md-center-tabs id=" ...

How to style a div for printing using CSS

Currently, I am working on a project that has already been completed but now requires some enhancements. To give you an overview, the project includes a search functionality that displays additional details upon clicking on the displayed name in the result ...

Using AJAX to dynamically load content from a Wordpress website

Currently, I have been experimenting with an AJAX tutorial in an attempt to dynamically load my WordPress post content onto the homepage of my website without triggering a full page reload. However, for some reason, when clicking on the links, instead of ...

Content Security Policy directive violation: Chrome extension policy error occured due to refusal to execute inline event handler

I've been working on a chrome extension to perform a simple task, but I've hit a roadblock with one line of HTML code that's causing issues with setting the correct permissions. Despite my efforts, I'm stuck on what exactly needs to be ...