Skip to content

Instantly share code, notes, and snippets.

@maicong
Created November 12, 2016 05:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maicong/38bc28e509d14097f4ba5f7374091624 to your computer and use it in GitHub Desktop.
Save maicong/38bc28e509d14097f4ba5f7374091624 to your computer and use it in GitHub Desktop.
获取微信表情包
((url, delay) => {
let starTime = new Date().getTime();
let xhr = new XMLHttpRequest();
let times = [];
let style = document.createElement('style');
style.textContent = 'body { background: #fff; } div { display: inline-flex; padding: 0.5rem; } div img { box-shadow: 0 0 5px 0 #8e8e8e; }';
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, timeStamp) => new Promise(resolve => {
let img = new Image();
let div = document.createElement('div');
img.src = src;
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);
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) / 1000;
let max = Math.max.apply(null, times) / 1000;
let sum = Math.round(times.reduce((p, c) => Number(p) + Number(c))) / 1000;
let avg = Math.round(sum / times.length);
console.debug(`图片下载完毕,用时 ${sum} s, 最快 ${min} s,最慢 ${max} s,平均 ${avg} s`);
} else {
i += 1;
promise(srcs[i].url, timeStamp);
}
}))(srcs[i].url, event.timeStamp);
})(0, (JSON.parse(xhr.responseText)));
}
};
xhr.send();
})('https://raw.githubusercontent.com/spacelan/wechat-emoticon/master/emoticons.json', 50);
@shipsywor
Copy link

What does it do? Can you please write a comment and how to use it?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment