In a custom component, is it faster to load styles in style tags or use a link tag?

Viewed 72

I'm working on some custom components and I'm wondering if it's best practice to load the styles in style tags within the template or use a link tag (rel="stylesheet") to call the styles?

Using style tags

const template = document.createElement('template');
template.innerHTML = `
  <style>
    .class-one {property: value;}
    .class-two {property: value;}
  </style>
  <div class="class-one class-two">
    <a href=""><slot></slot></a>
  </div>
`;

vs. using a link tag

const template = document.createElement('template');
template.innerHTML = `
  <link rel="stylesheet" href="path/to/styles.css">
  <div class="class-one class-two">
    <a href=""><slot></slot></a>
  </div>
`;

Is one of these provide better performance? How can I test to see which option loads the element faster?

1 Answers

It depends on what kind of performance you have in mind.

When using a <link> element, your users will benefit from client-side caching. This also means that you don't have to include your CSS inside your JS/HTML, resulting in a lot less bandwidth usage (and indirectly the effort taken to parse those).

Related