-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathhtml-import.js
More file actions
62 lines (57 loc) · 1.61 KB
/
Copy pathhtml-import.js
File metadata and controls
62 lines (57 loc) · 1.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/**
* @description 借助废弃的html import语法实现HTML或者其他代码片段的include功能
* 更多内容访问:https://www.zhangxinxu.com/wordpress/?p=10009
* @author zhangxinxu(.com)
* @create 2021-07-20
* @license MIT
*/
class HtmlImport extends HTMLLinkElement {
constructor () {
super();
}
static get observedAttributes () {
return ['href'];
}
load () {
fetch(this.href).then(res => {
if (res.ok) {
return res.text();
}
this.dispatchEvent(new CustomEvent('error', {
detail: {
error: '加载失败',
response: res
}
}));
}).catch(error => {
// 触发error事件
this.dispatchEvent(new CustomEvent('error', {
detail: {
error: '网络异常',
response: {
ok: false,
status: -1,
statusText: error
}
}
}));
}).then(html => {
if (typeof html == 'string') {
this.style.display = 'block';
this.innerHTML = html;
// 触发load事件
this.dispatchEvent(new CustomEvent('load'));
}
});
}
attributeChangedCallback (name) {
if (name == 'href') {
this.load();
}
}
}
if (!customElements.get('ui-import')) {
customElements.define('ui-import', HtmlImport, {
extends: 'link'
});
}