Question: How can I know that an image variable has successfully loaded an image from an image url?
The relevant javascript code I have been using is below (I am coding a Chrome extension). I want to grab a random image from an array of images, so I can use (inject) the random image on a webpage. But since I am grabbing the images off some websites that have tons of free images, I want to make sure the random image is not blocked by the free images website for whatever reason (and if it is blocked, then I will try another random image from maybe another site). I need to know that img.src contains an actual image or not. I am new to javascript, reading a book on it I just got yesterday-- do I need the semicolons or should I just ditch using semicolons? (I come from a background coding in C/C )
const myImages = [];
myImages[0] = 'https://cdn.pixabay.com/photo/2017/02/08/11/09/rainforest-2048447_960_720.jpg';
myImages[1] = 'https://images.freeimages.com/images/large-previews/01a/snail-1397758.jpg';
myImages[2] = 'https://cdn.pixabay.com/photo/2017/09/17/20/35/sloth-2759724_960_720.jpg';
const img = document.createElement('img');
img.src = myImages[Math.floor(Math.random()*myImages.length)];
img.style.width = '100%';
img.style.height = 'auto';
document.querySelector('#pageContent').replaceWith(img);
CodePudding user response:
You can use the code below
function checkExist() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log("exist")
}
};
xhttp.open("GET",
"https://cdn.pixabay.com/photo/2017/02/08/11/09/rainforest-2048447_960_720.jpg",true);
xhttp.send();
}
CodePudding user response:
You should write logic if image not loaded on image load error.
const myImages = [];
myImages[0] = 'https://cdn.pixabay.com/photo/2017/02/08/11/09/rainforest-2048447_960_720.jpg';
myImages[1] = 'https://images.freeimages.com/images/large-previews/01a/snail-1397758.jpg';
myImages[2] = 'https://cdn.pixabay.com/photo/2017/09/17/20/35/sloth-2759724_960_720.jpg';
const img = document.createElement('img');
img.src = myImages[Math.floor(Math.random()*myImages.length)];
img.style.width = '100%';
img.style.height = 'auto';
document.querySelector('#pageContent').replaceWith(img);
img.onerror = function() {
// If image not loaded, write your logic here
};
<div id="pageContent">imaged</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
Try to use es6 template literals and instead of template literals use img tag with properties
Var img <img src=${myImages.Math.floor(Math.random()*myImages.length)} width = '100%' height = 'auto'
document.querySelector('#pageContent').appendChield(img);