HTML meta标签大家都比较熟了。
其中http-equiv
属性,可以用来
设置过期时间、提供网站关键词等用于SEO、设置字符集、等等。
<!-- 设置过期时间(不缓存) -->
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Cache-Control" content="no-cache">
<meta http-equiv="Expires" content="0">
<!-- 关键词 -->
<meta http-equiv="keywords" content="keyword,keywords,keywords">
<meta http-equiv="description" content="this is description">
<!-- 字符集 -->
<meta http-equiv="content-Type" content="text/html;charset=gb2312">
等等。今天要记录的一个是用来刷新网站的refresh属性。
<!-- 5s后刷新 -->
<meta http-equiv="refresh" content="5" >
<!-- 5s后跳转到新浪网 -->
<meta http-equiv="refresh" content="5;URL=https://sina.cn" >
既然可以定时刷了,那么我就可以用他来代替定时器,主页面创建一个iframe,子页面定时刷新,然后通过postMessage
传递到主页面。
闲话不多说,代码如下:
let sao = (() => {
let timers = {}
let i = 0
function _guid() {
return (+new Date()).toString(36) + (i++)
}
function _clear(id) {
if (timers[id]) {
window.removeEventListener('message', timers[id].cb)
timers[id].ifr.parentNode && timers[id].ifr.parentNode.removeChild(timers[id].ifr)
delete timers[id]
}
}
function _set(callback, millisec) {
let id = _guid()
// 应该肯定不会重复
if (timers[id]) {
_clear(id)
}
let ifr = document.createElement('iframe')
ifr.style.display = 'none'
timers[id] = {
ifr: ifr,
cb(e) {
if (e.data === 'refresh') {
callback()
}
}
}
window.addEventListener('message', timers[id].cb, false);
ifr.src = `data:text/html,
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="refresh" content="${Math.ceil(millisec / 1000)}">
<title>1</title>
</head>
<body>
<script>top.postMessage('refresh', '*');</script>
</body>
</html>
`
// 转个码更好
// ifr.src = 'data:text/html,%3C%21DOCTYPE%20html%3E%0A%3Chtml%3E%0A%3Chead%3E%0A%09%3Cmeta%20charset%3D%22utf-8%22%20%2F%3E%0A%09%3Cmeta%20http-equiv%3D%22refresh%22%20content%3D%22' + Math.ceil(millisec / 1000) + '%22%20id%3D%22metarefresh%22%20%2F%3E%0A%09%3Ctitle%3Ex%3C%2Ftitle%3E%0A%3C%2Fhead%3E%0A%3Cbody%3E%0A%09%3Cscript%3Etop.postMessage%28%27refresh%27%2C%20%27%2A%27%29%3B%3C%2Fscript%3E%0A%3C%2Fbody%3E%0A%3C%2Fhtml%3E'
document.body.insertBefore(ifr, document.body.childNodes[0])
return id
}
return {
setInterval: _set,
clearInterval: _clear
}
})()
// 使用
let i = 0;
sao.setInterval(function() {
document.querySelector('p').innerHTML = ++i;
}, 1000)```
网友评论