dongzouqie4220 2018-12-04 21:33
浏览 42

在大型图库中一次加载一张图片

I am trying to reduce my website's loading time by placing a loading effect in the place of all img tags, and once the image loads the loading effect should disappear and actual image should fade in in the container.

My current try looks like the following:

Images are placed in markup as follows:

foreach ( $results['gallery'] as $gallery ) {
    $imgName = $gallery->photo;
    array_push($pictures, $gallery->photo);
    echo '<img class="photo" src="'.$path.$imgName. '" alt="">';
}

js:

$(document).ready(function() {
    $(".photo").hide().each(function() {
        var loader = new Image();
        $(loader).hide();
        $(loader).on('load', function() {
            console.log($(this).attr('src') + " loaded");
            $(this).fadeIn(700);
        })
        loader.src = $(this).attr('src');

    });
});

The desired outcome is to place each src into an Image() object and once that manages to load the picture in the background, the current .photo should fade in.

However, what actually happens is that even though the console.log statement has not yet appeared in the console, the image is already shown and the user can see that the browser is slowly loading the image (we are talking lots of 10+ MB pictures, so on a throttled connection its as if this piece of code wasnt even in the .js).

Another issue with this current approach is that images seem to start loading bottom to top of the markup (e.g. the very last picture in the markup is the first one to load), which I also havent managed to solve.

I have also tried initially putting the source in to data-src tag, iterating through them and loading them one by one in a similar fashion (utilising Image object), and on load the img tag would have their src set, however this has not worked at all. How could I modify my current approach so that the onload actually behaves?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 touchsocket udp组播
    • ¥20 MAC怎么安装Silverlight 插件?以及安装了怎么启用
    • ¥15 VS2012中查询语句无法填入解析,数值传不进去
    • ¥15 gis系统开发出现命名空间“ESRI.ArcGIS”中不存在类型或命名空间名“Analyst3D”报错
    • ¥15 怎么让ai定时给我发信息 c#或者python
    • ¥15 scrapy的Error
    • ¥15 RBF-VSG姚凤军论文复现问题
    • ¥30 开发一个APP商城在制作tabbar的时候运行不了代码没有检查出错误,但是显示不出tabbar,以下为运行结果,如何解决?
    • ¥15 多网卡服务器中winform如何绑定指定网卡
    • ¥15 关于#python#pandas#的问题,想要实现:多个TXT导入Excel,进行分列,不同txt之间都从第一行开始,请各位专家解答!