Last active
November 7, 2016 16:21
Star
You must be signed in to star a gist
获取 B 站右上角所有小图的 JS 代码 -> https://maicong.me/t/202
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
((url, delay) => { | |
let starTime = new Date().getTime(); | |
let xhr = new XMLHttpRequest(); | |
let times = []; | |
let style = document.createElement('style'); | |
style.textContent = 'body { display: flex; flex-wrap: wrap; } div { text-align: center; padding: 0.5rem; margin: 1rem; border: 1px solid #ddd; }'; | |
document.head.appendChild(style); | |
document.body.innerHTML = ''; | |
xhr.open('GET', url, true); | |
xhr.onload = event => { | |
if (xhr.status >= 200 && xhr.status < 400) { | |
console.debug(`资源已加载,耗时 ${new Date().getTime() - starTime} ms,开始获取...`); | |
(loadImg = (i, srcs) => { | |
(promise = (src, title, timeStamp) => new Promise(resolve => { | |
let img = new Image(); | |
let div = document.createElement('div'); | |
let p = document.createElement('p'); | |
p.textContent = title; | |
img.src = src; | |
img.alt = title; | |
img.onload = newEvent => { | |
setTimeout(() => { | |
let usedTime = newEvent.timeStamp - timeStamp; | |
usedTime = Math.floor(i > 0 ? usedTime - delay : usedTime); | |
times.push(usedTime); | |
console.info(`第 ${i + 1} 张获取成功,耗时 ${usedTime} ms`, img.src); | |
div.appendChild(img); | |
div.appendChild(p); | |
document.body.appendChild(div); | |
resolve(newEvent.timeStamp); | |
}, delay); | |
}; | |
img.onerror = err => { | |
console.warn(`第 ${i + 1} 张获取失败`, img.src); | |
resolve(err.timeStamp); | |
}; | |
}).then(timeStamp => { | |
if (i === srcs.length - 1) { | |
let min = Math.min.apply(null, times); | |
let max = Math.max.apply(null, times); | |
let avg = (times.reduce((p, c) => Number(p) + Number(c)) / times.length).toFixed(0); | |
console.debug(`图片下载完毕,最快用时 ${min} ms,最慢用时 ${max} ms,平均用时 ${avg} ms`); | |
} else { | |
i += 1; | |
promise(srcs[i].icon, srcs[i].title, timeStamp); | |
} | |
}))(srcs[i].icon, srcs[i].title, event.timeStamp); | |
})(0, (JSON.parse(xhr.responseText)).fix); | |
} | |
}; | |
xhr.send(); | |
})('http://www.bilibili.com/index/index-icon.json', 100); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment