Importing styles into a web component

Ben Aston picture Ben Aston · Feb 22, 2015 · Viewed 8k times · Source

What is the canonical way to import styles into a web component?

The following gives me an error HTML element <link> is ignored in shadow tree:

<template>
    <link rel="style" href="foo.css" />
    <h1>foo</h1>
</template>

I am inserting this using shadow DOM using the following:

var importDoc, navBarProto;

importDoc = document.currentScript.ownerDocument;

navBarProto = Object.create(HTMLElement.prototype);
navBarProto.createdCallback = function() {
  var template, templateClone, shadow;

  template = importDoc.querySelector('template');
  templateClone = document.importNode(template.content, true);

  shadow = this.createShadowRoot();
  shadow.appendChild(templateClone);
};

document.registerElement('my-nav-bar', {
  prototype: navBarProto
});

Answer

Jammer picture Jammer · Jun 2, 2015

If you need to place external styles inside the <template> tag you could try

<style> @import "../my/path/style.css"; </style>

however I have a feeling this will start importing after the element has been created.