[removed] How can I delay returning a value for im

2019-02-10 18:39发布

问题:

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?

回答1:

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.