懒加载机制中获取图片自然尺寸并调整大小的问题与解决
懒加载图片的尺寸适配问题:未等待onload完成导致计算失败
我需要在懒加载机制中调整图片尺寸,启用懒加载时图片的最终路径存储在data-src属性中。出于视觉效果考虑,不想等待懒加载完成,于是编写了以下代码:
window.addEventListener('load', function() { const aImages = document.getElementsByClassName('article-image'); for ( var i=0;i<aImages.length;i++ ) { const wrp = aImages[i].parentElement; var imgHeight, imgWidth; // 处理懒加载图片 if ( aImages[i].getAttribute('data-src') ) { var img = new Image(); img.onload = function() { imgHeight = this.naturalHeight; imgWidth = this.naturalWidth }; img.src = aImages[i].getAttribute('data-src'); } else { imgHeight = aImages[i].naturalHeight; imgWidth = aImages[i].naturalWidth; } var dim = calcAspectRatioFit(imgWidth, imgHeight, wrp.clientWidth, wrp.clientHeight); console.log('['+i+']\n' + 'dim.width: '+dim.width + '\ndim.height: '+dim.height + '\ntypeof(wrp): '+typeof(wrp) + '\nwrp.clientWidth: '+wrp.clientWidth + '\nwrp.clientHeight: '+wrp.clientHeight + '\nimgWidth: '+imgWidth + '\nimgHeight: '+imgHeight); aImages[i].style.setProperty('width', dim.width + 'px', 'important'); aImages[i].style.setProperty('height', dim.height + 'px', 'imoprtant'); } });
我猜测问题出在onload函数上——如果在onload和calcAspectRatioFit()之间设置断点,一切能正常工作,推测此时图片有足够时间加载完成。
控制台调试输出:
[0] dim.width: NaN dim.height: NaN typeof(wrp): object wrp.clientWidth: 222 wrp.clientHeight: 192 imgWidth: undefined imgHeight: undefined
请问有什么解决办法?
编辑:解决方案
问题核心是最后四行代码没有等待img.onload()执行完成。以下是可用的快速解决方案(通过匿名包装函数复制循环变量i):
window.addEventListener('load', function() { const aImages = document.getElementsByClassName('article-image'); const exec = function(i) { const wrp = aImages[i].parentElement; var dim = calcAspectRatioFit(aImages[i].naturalWidth, aImages[i].naturalHeight, wrp.clientWidth, wrp.clientHeight); aImages[i].style.setProperty('width', dim.width + 'px'); aImages[i].style.setProperty('height', dim.height + 'px'); } for ( var i=0;i<aImages.length;i++ ) { if ( aImages[i].getAttribute('data-src') ) { aImages[i].onload = (function(i) { return function() { exec(i) } })(i); this.src = aImages[i].getAttribute('data-src'); } else { exec(i) } } });
内容的提问来源于stack exchange,提问作者stuck1a
相关产品推荐
相关产品推荐

