延迟(延迟)加载背景图像?
Deferred (lazy) loading of background images?
我正在使用一个简单的脚本来延迟加载页面上的所有图像;图像源的路径包含在 data-src
属性中,然后放入 img
标签的实际 src
属性中。几乎大多数(?)延迟加载方法的实现是如何工作的。
这是脚本:
[].forEach.call(document.querySelectorAll('img[data-src]'), function(img) {
img.setAttribute('src', img.getAttribute('data-src'));
img.onload = function() {
img.removeAttribute('data-src');
};
});
我也想使用相同的脚本来延迟加载背景图像。我必须如何更改它才能使 data-src
属性最终出现在 div
的 background-image
-属性 的 url
值中?
我尝试了以下但没有结果,因为脚本无法将 background-image
识别为 属性:
[].forEach.call(document.querySelectorAll('div[data-src]'), function(div) {
div.setAttribute('background-image', div.getAttribute('data-src'));
div.onload = function() {
div.removeAttribute('data-src');
};
});
问题可能出在作为属性的背景图片上。您是否尝试过使用背景图片设置样式?
[].forEach.call(document.querySelectorAll('div[data-src]'), function(div) {
div.setAttribute("style","background-image: url(" + div.getAttribute('data-src') + ");");
div.onload = function() {
div.removeAttribute('data-src');
};
});
[].forEach.call(document.querySelectorAll('div[data-src]'), function(div) {
div.style.backgroundImage="url('" + div.getAttribute('data-src') + "')";
div.onload = function() {
div.removeAttribute('data-src');
};
});
试试这个
我正在使用一个简单的脚本来延迟加载页面上的所有图像;图像源的路径包含在 data-src
属性中,然后放入 img
标签的实际 src
属性中。几乎大多数(?)延迟加载方法的实现是如何工作的。
这是脚本:
[].forEach.call(document.querySelectorAll('img[data-src]'), function(img) {
img.setAttribute('src', img.getAttribute('data-src'));
img.onload = function() {
img.removeAttribute('data-src');
};
});
我也想使用相同的脚本来延迟加载背景图像。我必须如何更改它才能使 data-src
属性最终出现在 div
的 background-image
-属性 的 url
值中?
我尝试了以下但没有结果,因为脚本无法将 background-image
识别为 属性:
[].forEach.call(document.querySelectorAll('div[data-src]'), function(div) {
div.setAttribute('background-image', div.getAttribute('data-src'));
div.onload = function() {
div.removeAttribute('data-src');
};
});
问题可能出在作为属性的背景图片上。您是否尝试过使用背景图片设置样式?
[].forEach.call(document.querySelectorAll('div[data-src]'), function(div) {
div.setAttribute("style","background-image: url(" + div.getAttribute('data-src') + ");");
div.onload = function() {
div.removeAttribute('data-src');
};
});
[].forEach.call(document.querySelectorAll('div[data-src]'), function(div) {
div.style.backgroundImage="url('" + div.getAttribute('data-src') + "')";
div.onload = function() {
div.removeAttribute('data-src');
};
});
试试这个