Image fetch
HTML
<div id="image_container"></div>
JavaScript
let urlCreator = window.URL || window.webkitURL;
// Helper function for making ajax requests
let fetch = function(url) {
return $.ajax({
type: "get",
xhrFields:{
responseType: "blob"
},
url: url,
});
};
// Map the array of urls to an array of ajax requests
let urls = ["https://placekitten.com/200/250", "https://placekitten.com/300/250"];
let files = urls.map(url => fetch(url));
// Use the spread operator to wait for all requests
$.when(...files).then(function() {
if(urls.length > 1) {
// Create image sources and tags for each result
Array.from(arguments).forEach((data, index) => {
let imageUrl = urlCreator.createObjectURL(data[0]);
let img = `<a href="${urls[index]}" target="_blank">
<img src=${imageUrl}>
</a>`;
$("#image_container").append(img);
});
}
else {
// Create image source and tag for result
let imageUrl = urlCreator.createObjectURL(arguments[0]);
let img = `<a href="${urls[0]}" target="_blank">
<img src=${imageUrl}>
</a>`;
$("#image_container").append(img);
}
});