JSFiddle - React, Tailwind, and code Playground
HTML
<input placeholder="URL of Image" style="width:100%">
<button>load image</button>
<p></p>
JavaScript
function loadImg(options, callback) {
var seconds = 0,
maxSeconds = 10,
complete = false,
done = false;
if (options.maxSeconds) {
maxSeconds = options.maxSeconds;
}
function tryImage() {
if (done) {
return;
}
if (seconds >= maxSeconds) {
callback({
err: 'timeout'
});
done = true;
return;
}
if (complete && img.complete) {
if (img.width && img.height) {
callback({
img: img
});
done = true;
return;
}
callback({
err: '404'
});
done = true;
return;
} else if (img.complete) {
complete = true;
}
seconds++;
callback.tryImage = setTimeout(tryImage, 1000);
}
var img = new Image();
img.onload = tryImage();
img.src = options.src;
tryImage();
}
$('button').click(function () {
$('img').remove();
$('p').text('');
loadImg({
src: $('input').val()
}, function (status) {
if (!status.err) {
$('body').append($(status.img));
$('p').text('success');
} else {
$('p').text(status.err);
}
});
});