Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 延迟加载图像,但使用img元素的标准语法_Javascript_Html_Image - Fatal编程技术网

Javascript 延迟加载图像,但使用img元素的标准语法

Javascript 延迟加载图像,但使用img元素的标准语法,javascript,html,image,Javascript,Html,Image,我正在制作一个小型的惰性加载程序,目前看起来如下: <!-- an image --> <div data-image-src="http://lorempixel.com/450/350/" width="450" height="350" style="width:450px;height:350px" ></div> <script> // Lazy load all images var elements = docume

我正在制作一个小型的惰性加载程序,目前看起来如下:

<!-- an image -->

<div data-image-src="http://lorempixel.com/450/350/" width="450" height="350" style="width:450px;height:350px" ></div>
<script>
    // Lazy load all images
    var elements = document
        .querySelectorAll('[data-image-src]');

    Array.prototype.forEach.call(elements, function(element) {
        var image   = document.createElement("img"),
            parent  = element.parentElement,
            src     = element.getAttribute('data-image-src');

        for (var attr in element.attributes) {
            if ( element.attributes.hasOwnProperty(attr) && attr !== 'length' ) {
                image.setAttribute(element.attributes[attr].name, element.attributes[attr].value);
            }
        }

        image.src = src;
        image.onload = function() { parent.replaceChild(image, element); }
    });
</script>

//延迟加载所有图像
var元素=文档
.querySelectorAll(“[data image src]”);
Array.prototype.forEach.call(元素,函数(元素){
var image=document.createElement(“img”),
parent=element.parentElement,
src=element.getAttribute('data-image-src');
for(element.attributes中的var attr){
if(element.attributes.hasOwnProperty(attr)&&attr!='length'){
image.setAttribute(element.attributes[attr].name,element.attributes[attr].value);
}
}
image.src=src;
image.onload=function(){parent.replaceChild(image,element);}
});
正如您所看到的,图像元素非常难看。我只想取消图像上
属性的加载

我特别感兴趣的是,它们具有
src
属性。我的目标是能够使用具有有效、规则语法的图像标记,并且能够延迟加载它们

这是否可能,也许可以暂时替换
HTMLImageElement
原型方法之一

谢谢



为什么不使用一个透明的占位符,然后在加载事件中替换掉src呢?

这个问题更多的是针对具有正常语法的图像实现延迟加载
<img src="1x1.png" data-image-src="http://lorempixel.com/450/350/" width="450" height="350" style="width:450px;height:350px" />