0

i would like to know how i could add image attributes to the following code. I've added a teest function to see if the users browser supports webp image and if it doesn't it just shows a jpg image instead of webp but i want to add attributes and nothing i've done works.

function hasWebP() {
  var rv = $.Deferred();
  var img = new Image();
  img.onload = function() { rv.resolve(); };
  img.onerror = function() { rv.reject(); };
  img.src = '/images/home/dot.webp';
  return rv.promise();
}
hasWebP().then(function() {
    var img=document.createElement("img");
    img.src="images/home/IMG_4389.webp";
    img.id="picture";
    var foo = document.getElementById("myFace");
    foo.appendChild(img);
}, function() {
    var img=document.createElement("img");
    img.src="images/home/IMG_4389.png";
    img.id="picture2";
    var foo = document.getElementById("myFace");
    foo.appendChild(img);
});
1
  • Have you tested the img src urls? I tested with img.src="/images/home/IMG_4389.png" (note the / at the start of the src) and it appended the image to the DOM for me Commented Apr 21, 2018 at 0:35

1 Answer 1

1

I changed my code to

function hasWebP() {
  var rv = $.Deferred();
  var img = new Image();
  img.onload = function() { rv.resolve(); };
  img.onerror = function() { rv.reject(); };
  img.src = '/images/home/dot.webp';
  return rv.promise();
}
hasWebP().then(function() {
    document.getElementById("picture").src="/images/home/IMG_4389.webp";
}, function() {
    document.getElementById("picture").src="/images/home/IMG_4389.png";
});

And added this to my html

<img src="" id="picture" draggable="false">
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.