当前位置: 首页 > news >正文

JavaScript使用webcomponent的简单示例

官方网站:

Web Component - Web API 接口参考 | MDN

1. 给一个html文件的路径字符串path, 存储对应path下的template,script,style数据

1) 传入path

2) 使用fetch将path字符串所在的文件找到并返回内容

const res = await fetch(path).then(res => res.text());

3) 使用DOMParser实例的parseFromString方法将至转换为shadowRoot

const parser = new DOMParser();
const doc = parser.parseFromString(res, "text/html"); // shadowRoot

4) shadowRoot支持dom查找元素的方法, 可以找到template, script, style标签元素

5) 根据不同的path, 存放相应的template, script, style

// 动态加载组件并解析
async function loadComponent(path, name) {this.caches = this.caches || {};// 当缓存存在if (!!this.caches[path]) {return this.caches[path]}const res = await fetch(path).then(res => res.text());// 利用DOMParser,生成shaow-rootconst parser = new DOMParser();const doc = parser.parseFromString(res, "text/html");// 解析模板,脚本,样式const template = doc.querySelector("template");const script = doc.querySelector("script");const style = doc.querySelector("style");// 缓存内容this.caches[path] = {template,script,style}return this.caches[path]
}

2. custom-component.js(自定义标签custom-component)

// 容器组件
class CustomComponent extends HTMLElement {async connectedCallback() {console.log("custom-component connected");// 获取组件的path,即html的路径const strPath = this.getAttribute("path");// 加载htmlconst cInfos = await loadComponent(strPath);// Element.attachShadow() 方法给指定的元素挂载一个 Shadow DOM,并且返回对 ShadowRoot 的引用。const shadow = this.attachShadow({ mode: "closed" });// 添加html对应的标签和内容this._addElements(shadow, cInfos);}_addElements(shadow, info) {if (info.template) {shadow.appendChild(info.template.content.cloneNode(true));}if (info.script) {var fn = new Function(`${info.script.textContent}`);// 绑定脚本的this为当前的影子根节点, 防止全局污染fn.call(shadow);}if (info.style) {shadow.appendChild(info.style);}}
}
window.customElements.define("custom-component", CustomComponent);

使用自定义标签custom-component

// 使用示例: renderComponent.call(thisArg, route)
function renderComponent(route) {var el = document.createElement("custom-component");el.setAttribute("path", `/${route.component}.html`);// append可以追加节点和字符串,appendChild只能追加节点;el.id = "_route_";this.append(el);
}

1) 先新建goods.html

<template><div>商品详情-goos</div><div class="product-id">下面商品是????</div>
</template><script>alert('这是商品页!!!')
</script><style>.product-id{color: red;}
</style>

2) 在index.html使用

先引入custom-component.js

然后在index.html的script标签写:

renderComponent.call(document.getElementById('box'), {component: './goods'})

index.html文件代码

<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>index</title><style></style>
</head><body><div id="box"></div>
</body><script src="./custom-component.js"></script><script>renderComponent.call(document.getElementById('box'), {component: './goods'})</script>
</html>

http://www.lryc.cn/news/229995.html

相关文章:

  • LeetCode(10)跳跃游戏 II【数组/字符串】【中等】
  • 浅谈数据结构之递归
  • 在CentOS7环境下安装Mysql
  • 苍穹外卖-day10
  • 牛客网刷题笔记131111 Python实现LRU+二叉树先中后序打印+SQL并列排序
  • TCP网络编程
  • K8S知识点(九)
  • el-table实现单选和隐藏全选框和回显数据
  • 香港科技大学广州|智能制造学域机器人与自主系统学域博士招生宣讲会—中国科学技术大学专场
  • [P7885][Android13] 解决5G信号良好状态栏信号只有两格的问题
  • 老版本goland无法调试新版本go问题处理
  • Redis应用之二分布式锁2
  • 打印字符(C++)
  • React函数组件的使用(Hooks)
  • 一篇博客读懂队列——Queue
  • Effective C++ 系列和 C++ Core Guidelines 如何选择?
  • Sandbox: bash(5613) deny(1) file-write-create 错误解决
  • 腾讯云标准型S5服务器五年优惠价格表(4核8G和2核4G)
  • Nginx 是如何解决惊群效应的?
  • 【深度学习实验】网络优化与正则化(三):随机梯度下降的改进——Adam算法详解(Adam≈梯度方向优化Momentum+自适应学习率RMSprop)
  • 如何解决网页中的pdf文件无法下载?pdf打印显示空白怎么办?
  • 【JVM】类加载器 Bootstrap、Extension、Application、User Define 以及 双亲委派
  • 读书笔记:彼得·德鲁克《认识管理》第15章 使工作富有成效:工作和过程
  • 媒体软文投放的流程与媒体平台的选择
  • 【excel技巧】如何取消excel隐藏?
  • AIGC专栏8——EasyPhoto 视频领域拓展-让AIGC肖像动起来
  • C++ RBTree 理论
  • 制作这种在线宣传画册,可轻松收获客户!
  • 数据结构 | 图
  • [文件读取]shopxo 文件读取(CNVD-2021-15822)