3

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?

Millhorn
  • 2,953
  • 7
  • 39
  • 77

1 Answers1

2

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).

Kelvin Schoofs
  • 8,323
  • 1
  • 12
  • 31
  • 1
    @Millhorn An `async` stylesheet will just load at a later time when the page finished loading and is less busy. That means there'll be a small amount of time where your components won't be styled. You can also combine all stylesheets into one `.css` file for which you'd only need a single `` in your page. That's also what bundlers such as [Webpack](https://webpack.js.org/) do. It combines all the CSS files in your project (and dependencies) and bundles them together into a single CSS file, linked in your HTML. – Kelvin Schoofs Jul 22 '21 at 15:43
  • Thank you for answering. I deleted my comment because I realize you can't `async` or `defer` stylesheets, but rather use `rel="preload"`, which has similar behavior. – Millhorn Jul 22 '21 at 16:02