You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过PHP文件加载页面图片并等待全部加载完成后再显示

实现方案

第一步:修改index.php完整代码

<html>
  <head>
    <title>Image Load</title>
    <style>
      .img-container {
        position: relative;
        width: 300px;
        height: 200px;
        margin: 10px;
        display: inline-block;
        background: #f5f5f5;
        border-radius: 4px;
        overflow: hidden;
      }
      /* 单图加载动画 */
      .img-container::after {
        content: '';
        position: absolute;
        top: 50%;
        left: 50%;
        width: 24px;
        height: 24px;
        margin: -12px 0 0 -12px;
        border: 2px solid #e0e0e0;
        border-top-color: #2196F3;
        border-radius: 50%;
        animation: spin 0.8s linear infinite;
      }
      @keyframes spin {
        to {transform: rotate(360deg);}
      }
      .lazy-image {
        width: 100%;
        height: 100%;
        object-fit: cover;
        opacity: 0;
        transition: opacity 0.6s ease;
      }
      /* 淡入动画类 */
      .lazy-image.appear {
        opacity: 1;
      }
      .img-container.loaded::after {
        display: none;
      }
    </style>
  </head>
  <body>
    <?php 
      $images = glob('images/*.png');
      foreach($images as $image){
        echo('<div class="img-container"><img src="image.php?i='.urlencode($image).'" class="lazy-image"></div>');
      }
    ?> 
    <script>
      document.addEventListener('DOMContentLoaded', () => {
        const images = document.querySelectorAll('.lazy-image');
        let loadedCount = 0;
        const totalImages = images.length;

        const checkAllLoaded = () => {
          if (loadedCount === totalImages) {
            images.forEach(img => {
              img.classList.add('appear');
              img.parentElement.classList.add('loaded');
            });
          }
        };

        images.forEach(img => {
          img.addEventListener('load', () => {
            loadedCount++;
            checkAllLoaded();
          });
          // 加载失败也计数,避免页面一直处于加载状态
          img.addEventListener('error', () => {
            loadedCount++;
            // 加载失败默认占位图,可自行替换
            img.src = 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzAwIiBoZWlnaHQ9IjIwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cmVjdCB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiBmaWxsPSIjZWVlIi8+PHRleHQgeD0iNTAlIiB5PSI1MCUiIGZvbnQtc2l6ZT0iMTQiIGZpbGw9IiM5OTkiIHRleHQtYW5jaG9yPSJtaWRkbGUiIGR5PSIuM2VtIj7lpKfniYflpIfotqE8L3RleHQ+PC9zdmc+';
            checkAllLoaded();
          });
        });
      });
    </script>
  </body>
</html>

注:可根据实际需求调整.img-container的宽高尺寸,也可以设置为自适应布局。如果不需要单图加载动画,直接删除.img-container::after相关样式即可。

第二步:修复image.php存在的小问题

原代码else分支中$file变量未定义,会抛出PHP警告,修改为$path即可:

<?php
  $path = urldecode($_GET['i']);

  if (file_exists($path)) {
    $extension = pathinfo($path)['extension'];
      header('Content-type:'.$extension);
      header('Cache-control:public, max-age=604800');
      header('Accept-ranges:bytes');
      header('Content-length:'.filesize($path));
      header('Last-Modified: '.date(DATE_RFC2822, filemtime($path)));
      header_remove('pragma');
      echo(file_get_contents($path));
  }
  else {
    echo("File not found: ".$path);
  }
?>

说明

  • 原代码中的loading="lazy"属性已移除,该属性会让浏览器只加载视口内的图片,拖慢全部图片加载完成的时间,不符合全量加载后统一显示的需求
  • 代码兼容图片加载失败的场景,不会因为个别图片加载异常导致所有图片都无法显示
  • 淡入动画时长可通过修改.lazy-image的transition参数自定义

内容的提问来源于stack exchange,提问作者MrMills

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 10:18:02