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

1

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?

Uprear answered 22/7, 2021 at 15:29 Comment(0)
A
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).

Afire answered 22/7, 2021 at 15:33 Comment(2)
@Uprear 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 <link> in your page. That's also what bundlers such as Webpack 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.Afire
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.Uprear

© 2022 - 2024 — McMap. All rights reserved.