function test(url){ var str=undefined; var img =new Image() img.src=url img.onload=function(){ str=img } return str }
事实上test()直接就返回了undefined,说明onload要等待img资源都加再完成了才能执行,不能保证同步执行
解决方法一:
基于jQuery兼容性好
function test(url){ var img =new Image(); img.title='xxxx'; img.src=url; var deferred = $.Deferred(); img.onload=function () { deferred.resolve(img); } return deferred.promise(); } //图片地址加载有延迟 test('http://lorempixel.com/100/100?0.6412381180562079').then((res)=>{ console.log(res) //<img title="xxxx" src="http://lorempixel.com/100/100?0.6412381180562079"> })
解决方法二:
不需要任何第三方插件
function test(url){ return new Promise(function (a,b) { var img =new Image(); img.title='xxxx'; img.src=url; img.onload=function () { a(img) } }) } test('http://lorempixel.com/100/100?0.6412381180562079').then((res)=>{ console.log(res) })