Search code examples
javascripthtmldropzone.jscustom-elementhtml5-template

How to apply imported stylesheet to template tag content for a custom element?


Here is the code I am trying to use

<script type="text/javascript" src="dropzone.js"></script>
<link href="dropzone.css" rel="stylesheet"/>

<template id="dropzoneTemplate">
	<div id="dZUpload" class="dropzone">
		  <div class="dz-default dz-message"></div>
	</div>
</template>
<dropzone></dropzone>

<script>
    var DropzoneElementPrototype = Object.create(HTMLElement.prototype);

    DropzoneElementPrototype.createdCallback = function () {
        var t = document.querySelector('#uploadImageTemplate');
        var clone = document.importNode(t.content, true);
        this.createShadowRoot().appendChild(clone);
    };

    var DropzoneElement = document.registerElement('dropzone', {
        prototype: DropzoneElementPrototype
    });

</script>

But the imported stylesheet dropzone.css is not getting applied to the content inside template tag, i.e. class dropzone is not getting its styles from dropzone.css so the styles in the imported file is not getting applied to elements like div inside template tag.

I have also tried to put this link tag inside the template tag, but that doesn't work either.

Is it possible to apply imported stylesheet to template tag content for a custom element?


Solution

  • Use an @import css style rule inside your <template> element:

    <template id="dropzoneTemplate">
        <style>
           @import url( 'dropzone.css' )
        </style>
        <div id="dZUpload" class="dropzone">
              <div class="dz-default dz-message"></div>
        </div>
    </template>
    

    Note:

    • According to the CSS2 specification, @import rule must precede any other rules except @charset.

    • If your stylesheet defines a @font-face, it must be included in the main document too.