一个懒加载模板

参考 jekyll 主题 maximevaillancourt/digital-garden-jekyll-template 笔记图谱懒加载的 实现

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
<div id="test">
模块加载中……
</div>

<script>
let flag = true;

window.addEventListener("load", () => {
assertThenLoad();
});

window.addEventListener("scroll", () => {
assertThenLoad();
});

function assertThenLoad(){
if (canLoad()) {
loadModule();
}
}

function canLoad(){
return document.getElementById("test").getBoundingClientRect().top
< window.innerHeight
&& flag;
}

function loadModule() {
var oScript = document.createElement("script");

oScript.type = "text/javascript";
oScript.src = "https://leay.net/testmodule.js"; //需要懒加载的资源
document.body.appendChild(oScript);

oScript.onload = () => {
init();// 资源加载逻辑
};
flag = false;
}
</script>

比如本站 valine 评论区懒加载如下:

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
<div style="text-align: center; margin-top: 10px" id="load-comment">
评论区加载中……
</div>
<div id="vcomments" style="margin-top: 3rem"></div>
<script>
let commentFlag = true;

window.addEventListener("load", () => {
assertThenLoad();
});

window.addEventListener("scroll", () => {
assertThenLoad();
});

function assertThenLoad(){
if (canLoad()) {
loadModule();
}
}

function canLoad(){
return document.getElementById("vcomments").getBoundingClientRect().top
< window.innerHeight
&& commentFlag;
}

function loadModule() {
var oScript = document.createElement("script");

oScript.type = "text/javascript";
oScript.src = "//unpkg.com/valine/dist/Valine.min.js";
document.body.appendChild(oScript);

oScript.onload = () => {
new Valine({
el: "#vcomments",
appId: "app-id",
appKey: "app-key",
});
document.getElementById("load-comment").style.display = "none";
};
commentFlag = false;
}
</script>