Load source into a .ttf file from JavaScript

1

I am trying to add a source to my project, the issue is that I need to do everything from JS, how do I load a source from a .ttf file? since to apply the font-family I need the font to be already loaded (since apparently it only receives as parameter the name of the source, but not its absolute address).

    
asked by Cristofer Fuentes 27.11.2016 в 01:17
source

1 answer

3
  

Note: In all snippets a font Web Open Font Format 2 ( .woff2 ) is loaded, because I could not find a True Type ( .ttf ). In any case, the solutions apply equally for sources True Type .

I can think of 3 ways to dynamically load a font using javascript :

  • Creating a tag link and indicating the href to the file where the source is declared.
  • function loadFont() {
      var link = document.createElement('link');
      link.href = '//fonts.googleapis.com/css?family=Bungee+Inline';
      link.rel = 'stylesheet';
      document.head.appendChild(link);
    }
    
    //
    document.getElementById('cargar').addEventListener('click', loadFont);
    h1 {
      font-family: 'Bungee Inline', arial;
    }
    <h1>Hola Mundo!<h1>
    <button id="cargar">Cargar fuente</button>
  • Creating a style tag and use @import to load the source.
  • function loadFont() {
      var style = document.createElement('style');
      style.innerText = "@import url('https://fonts.googleapis.com/css?family=Bungee+Inline');";
      document.head.appendChild(style);
    }
    
    //
    document.getElementById('cargar').addEventListener('click', loadFont);
    h1 {
      font-family: 'Bungee Inline', arial;
    }
    <h1>Hola Mundo!<h1>
    <button id="cargar">Cargar fuente</button>
  • Creating a style tag and declaring the 'font-face' .
  • function loadFont() {
      var style = document.createElement('style');
      style.innerText = "@font-face {\
        font-family: 'Bungee Inline';\
        src: local('Bungee Inline'), local('BungeeInline-Regular'), url(https://fonts.gstatic.com/s/bungeeinline/v2/Tb-1914q4rFpjT-F66PLCTxObtw73-qQgbr7Be51v5c.woff2) format('woff2');\
      }";
      document.head.appendChild(style);
    }
    
    //
    document.getElementById('cargar').addEventListener('click', loadFont);
    h1 {
      font-family: 'Bungee Inline', arial;
    }
    <h1>Hola Mundo!<h1>
    <button id="cargar">Cargar fuente</button>
        
    answered by 27.11.2016 / 03:35
    source