views:

28

answers:

2

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?

A: 

Here's a script similar to yours that might serve as inspiration:

http://my.opera.com/Fyrd/blog/svg-image-and-background-image-replacer

Erik Dahlström
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.
stopsatgreen
A: 

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.

stopsatgreen