4

I am using LitElement and I am trying to load google-font at the element level.

I have tried returning it in an HTML literal in the connectedCallback event, but it does not work. I could not manage to do it in the get styles() method.

Where should the <link...> statement be placed in the code?

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
JoceM
  • 53
  • 1
  • 5
  • Possible duplicate of [How to use Font Awesome with Polymer LitElement](https://stackoverflow.com/questions/50342356/how-to-use-font-awesome-with-polymer-litelement) – Alan Dávalos Aug 14 '19 at 07:54

2 Answers2

1

You can import an external style sheet by adding a <link> element to your template, For details, see Import an external stylesheet.

Here's the demonstrate on StackBlitz.

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
0

You could import the google font in index.html easily:

<link href="https://fonts.googleapis.com/css?family=Kaushan+Script&display=swap" rel="stylesheet">

or you could create a common style.js file and include it:

const $_documentContainer = document.createElement('template');

$_documentContainer.innerHTML = `<style>
 @import url('https://fonts.googleapis.com/css?family=Kaushan+Script');
 html,
 body {
  font-family: 'Roboto', Arial, sans-serif;
  height: 100%;
  margin: 0;
 }
 ...


</style>`;

document.head.appendChild($_documentContainer.content);
var importDoc = window.document;
var style = importDoc.querySelector('style');
document.head.appendChild(style);

or:

class MyElement extends LitElement {
  render() {
    return html`
      <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Kaushan+Script">
    `;
  }
}

demo ( See the red a tag as I imported Kaushan+Script )

Cappittall
  • 3,300
  • 3
  • 15
  • 23
  • Thank you. I was actually looking for a solution to lazy-load fonts in components and not at the index level. Some fonts may only be required for specific components. I believe both your options load fonts upfront. – JoceM Aug 15 '19 at 08:52
  • @JoceM Did you find a solution for this? I'm also looking for a way to load the font inside the component and not at the index level... – Marcel Panse Sep 14 '20 at 12:36