效果:
目录:
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>Document</title><link rel="prefetch" href="index.js" as="script" onload="loadjs()"></head><body onload="load()"><a href="next.html">下一页</a><script>const loadjs = () => {console.log('index.js onload') }const load = () => {console.log('body onload')}</script></body>
</html>
next.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>Document</title><script src="index.js"></script>
</head>
<body>下一页了<script>let sum = add(1, 2)console.log(sum)</script>
</body>
</html>
index.js:
console.log('运行')const add = (a, b) => {return a + b
}
prefetch是一种利用浏览器的空闲时间加载页面将来可能用到的资源的一种机制;通常可以用于加载非首页的其他页面所需要的资源,以便加快后续页面的首屏速度;
prefetch特点:
prefetch加载的资源可以获取非当前页面所需要的资源,并且将其放入缓存至少5分钟(无论资源是否可以缓存);并且,当页面跳转时,未完成的prefetch请求不会被中断;