<!DOCTYPE html>
<html>
<head>
</head>
<body>
<style>
* {
border: none;
margin: 0;
outline: none;
padding: 0;
}
</style>
<custom-component-bug>
<h4>Buggy component.</h4>
</custom-component-bug>
<custom-component-working>
<h4>Working component.</h4>
</custom-component-working>
<script src="customComponentBug.js"></script>
<script src="customComponentWorking.js"></script>
</body>
</html>
class CustomComponentBug extends HTMLElement {
constructor() {
super();
this.template = '';
this.templateEl = document.createElement('template');
this.attachShadow({mode: 'open'});
window.customComponent = this;
}
connectedCallback() {
this.templateEl.innerHTML = `
<link rel="stylesheet" href="style1.css">
<div class="test">
<slot></slot>
<p id="height"></p>
<p id="heightLoaded"></p>
<p id="heightDelaied"></p>
</div>
`;
this.shadowRoot.appendChild(this.templateEl.content.cloneNode(true));
this.shadowRoot.querySelector('#height').innerHTML =
`Height after connect: host - <strong>${this.scrollHeight}</strong>`;
this.shadowRoot.querySelector('link').addEventListener('load', () => {
this.shadowRoot.querySelector('#heightLoaded').innerHTML =
`Hight after style load: host - <strong>${this.scrollHeight}</strong>`;
});
}
}
window.customElements.define('custom-component-bug', CustomComponentBug);
* {
border: 0;
margin: 0;
outline: 0;
padding: 0;
}
:host {
display: block;
contain: content;
position: relative;
}
.test {
background: red;
height: 200px;
}
class CustomComponentWorking extends HTMLElement {
constructor() {
super();
this.template = '';
this.templateEl = document.createElement('template');
this.attachShadow({mode: 'open'});
window.customComponent = this;
}
connectedCallback() {
this.templateEl.innerHTML = `
<link rel="stylesheet" href="style2.css">
<div class="test">
<slot></slot>
<p id="height"></p>
<p id="heightLoaded"></p>
<p id="heightDelaied"></p>
</div>
`;
this.shadowRoot.appendChild(this.templateEl.content.cloneNode(true));
this.shadowRoot.querySelector('#height').innerHTML =
`Height after connect: host - <strong>${this.scrollHeight}</strong>`;
// HACK workaround the bug
this.shadowRoot.appendChild(document.createElement('style'));
// end HACK
this.shadowRoot.querySelector('link').addEventListener('load', () => {
this.shadowRoot.querySelector('#heightLoaded').innerHTML =
`Hight after style load: host - <strong>${this.scrollHeight}</strong>,`;
});
}
}
window.customElements.define('custom-component-working', CustomComponentWorking);
* {
border: 0;
margin: 0;
outline: 0;
padding: 0;
}
:host {
display: block;
contain: content;
position: relative;
}
.test {
background: green;
height: 200px;
}