Javascript: How can I delay returning a value for img.complete
Asked Answered
F

1

4

I've written a script to test for SVG support in the IMG tag:

function SVGinIMG() {
  var SVGdata = 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNzUiIGhlaWdodD0iMjc1Ij48L3N2Zz4%3D'
  var i = document.createElement('img');
  i.setAttribute('src',SVGdata);
  return i.complete;
}
window.onload = function() {
  var hasSVG = SVGinIMG();
  alert(hasSVG);
}

This does what I want, except that when I run the script in WebKit browsers the complete property doesn't trigger the first time I load the page; when I refresh the page, it works as it should. The return function is running before the img has finished loading; what's the best method to delay this?

Frolic answered 21/9, 2010 at 10:33 Comment(2)
Here's a script similar to yours that might serve as inspiration: my.opera.com/Fyrd/blog/svg-image-and-background-image-replacerVharat
Ha! That's what I was looking at as part-inspiration for my script, but I thought it somewhat too complicated. But thanks for the link anyway, I'll study it a little more closely.Frolic
F
5

I was complicating things a little; all I really needed was the load event:

function SVGDetect() {
  var testImg = 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNzUiIGhlaWdodD0iMjc1Ij48L3N2Zz4%3D';
  var img = document.createElement('img')
  img.setAttribute('src',testImg);
  img.addEventListener('load',setCSS,true);
}

This runs another function when the image loads, which is never in the case of browsers that don't support SVG in images.

Frolic answered 21/9, 2010 at 13:49 Comment(1)
Not so fond of this version because it needs a callback rather than just returning true/false. Thanks for the original "question" at any rate! What's the advantage?Domel

© 2022 - 2024 — McMap. All rights reserved.