考虑一个简单的 Web 组件
class TimeAgo extends HTMLElement {
constructor() {
super();
this.innerHTML = '2 hours ago'
}
}
customElements.define('time-ago', TimeAgo);
这样使用
This post was created <time-ago datetime="2020-09-26T11:28:41.9731640+01:00">September 26th</time-ago>
当页面呈现时,浏览器将首先写入“9 月 26 日”,然后立即切换到“2 小时前”。
有没有办法防止这种情况发生?我更喜欢在第一次绘制时显示“2 小时”。
JS 文件是通过 CDN 加载的,上下移动脚本标签响应没有改变任何东西。
但是在解析 DOM 的该部分之前,您的元素是否已经定义并执行了其脚本?
下面的代码显示 1A,因为 1 是在之前 content A 被解析到 DOM 中的。
所以,如果你不想 FOUC 留下
<time-ago>
content 空..或者用 CSS 模糊它
<script>
window.onload = () => {
console.log("onload");
};
customElements.define(
"my-element",
class extends HTMLElement {
constructor() {
super();
console.log("constructor");
}
connectedCallback() {
console.log("connectedCallback");
this.innerHTML = "1";
}
}
);
</script>
<my-element>A</my-element>
<script>
console.log("end DOM");
</script>
我能想到的可能的解决方案之一是启用
shadow-dom
class TimeAgo extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.innerHTML = '2 hours ago'
}
}
customElements.define('time-ago', TimeAgo);
通过将 Web 组件定义为 Shadow dom,您甚至可以在将其附加到 DOM 之前更改内容。