当我尝试以两种不同的方式执行以下操作时,我在想区别在哪里,不是在使用方面,而是在性能方面影响:
使用图片标签
<img src='http://lorempixel.com/300/300/sports/2/'>
连同,比方说,
img{ width: 100px; height: 100px; }
使用div标签
<div class='test'></div>
连同,比方说,
.test{ background-image: url('http://lorempixel.com/300/300/sports/2/'); width: 100px; height: 100px; }
话虽如此,我想知道两种情况下何时加载图像。对于第一个,使用加载事件非常容易。但是对于第二个,div 案例,我应该如何检查?..我知道这种方式 OverHead ,但这是否意味着它会产生开销,为每个 div 分别实例化 Image
?
是否有其他可能的方法来实现相同的目标?
最佳答案
为onload 事件添加一个事件监听器。
The onload attribute fires when an object has been loaded.
onload is most often used within the element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.). However, it can be used on other elements as well.
那么如何将其应用于第 2 种情况?
$('<img/>').attr('src', 'IMAGE_SOURCE_LINK').load(function() {
$(this).remove();
$('element').css('background-image', 'url('IMAGE_SOURCE_LINK')');
});
以上代码仅显示了我的意思。浏览器不会重新加载图像,因为它们保留在浏览器内存中,浏览器只加载一次。
关于javascript - 找出div背景图像已加载的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28743239/