Skip to content

Instantly share code, notes, and snippets.

@cou929
Last active December 22, 2022 09:01
Show Gist options
  • Save cou929/5334990 to your computer and use it in GitHub Desktop.
Save cou929/5334990 to your computer and use it in GitHub Desktop.
画像の読み込みにタイムアウトを付けたいけど XHR じゃないと厳しそう
<html>
<body>
<script type="text/javascript">
var blackhole_image_url = 'http://blackhole.webpagetest.org/',
wait_interval = 3000;
// 3秒じゃタイムアウトされない
loadWithImageElement(blackhole_image_url + 'element.png');
// 3秒じゃタイムアウトされない
loadWithImageObject(blackhole_image_url + 'object.png');
// 3秒でタイムアウト
loadWithXHR(blackhole_image_url + 'xhr.png');
window.setTimeout(function() {
window.stop();
}, wait_interval * 2);
function loadWithImageElement(src) {
var img = document.createElement('img');
img.setAttribute('id', 'img-target');
img.setAttribute('src', src);
document.body.appendChild(img);
window.setTimeout(function() {
console.log('abroting request from image element');
var target = document.getElementById('img-target');
target.removeAttribute('src');
target.parentElement.removeChild(target);
}, wait_interval);
}
function loadWithImageObject(src) {
var img = new Image();
img.src = src;
window.setTimeout(function() {
console.log('abroting request from image object');
img.src = '';
}, wait_interval);
}
function loadWithXHR(src) {
var xhr = new XMLHttpRequest();
xhr.open('GET', src);
xhr.send();
window.setTimeout(function() {
console.log('abroting request from xhr');
xhr.abort();
}, wait_interval);
}
</script>
<img src="http://gyazo.com/23c918a429be2791fd0ce63239e92399.png?1365407197" alt="sample result"/>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment