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?
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