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

落花浮王杯 提交于 2019-12-03 20:21:18

问题


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.



来源:https://stackoverflow.com/questions/3759427/javascript-how-can-i-delay-returning-a-value-for-img-complete

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!