如何异步预加载图像

How to asynchronously preload images

我有一组视频导出到帧并根据滚动位置显示当前帧(类似于 this 但使用图像帧而不是视频)

<head> 中使用它会导致很多初始延迟,但之后帧转换非常平滑。

<?php for ($i = 0; $i <= 99; $i++) {
    $number =  $i < 10 ? '0'.$i : $i; ?>
    <link rel="preload" href="<?php echo get_stylesheet_directory_uri()?>/media/frames/01/optim/_scene-1-00<?php echo $number; ?>.jpg" as="image">
<?php } ?>
<?php for ($i = 0; $i <= 99; $i++) {
    $number =  $i < 10 ? '0'.$i : $i; ?>
    <link rel="preload" href="<?php echo get_stylesheet_directory_uri()?>/media/frames/01/optim/_scene-2-00<?php echo $number; ?>.jpg" as="image">
<?php } ?>
<?php for ($i = 0; $i <= 99; $i++) {
    $number =  $i < 10 ? '0'.$i : $i; ?>
    <link rel="preload" href="<?php echo get_stylesheet_directory_uri()?>/media/frames/01/optim/_scene-3-00<?php echo $number; ?>.jpg" as="image">
<?php } ?>
...

有没有想过如何只预加载第一个场景,其余场景在 window.onload 之后预加载?

我最终是这样做的:

function preloadRestOfScenes() {
  /* Scene 2 */
  let html = "";
  for (let i = 0; i <= 249; i++) {
    let number;
    if (i < 10) {
      number = "00" + i;
    } else if (i >= 10 && i < 100) {
      number = "0" + i;
    } else {
      number = i;
    }
    html += `<link rel="preload" href="${stylesheet_directory_uri}/media/frames/02/optim/scene-2-${number}.jpg" as="image">`;
  }
  document.querySelector("head").insertAdjacentHTML("beforeend", html);

  /* Scene 3 */
  html = "";
  for (let i = 0; i <= 549; i++) {
    let number;
    if (i < 10) {
      number = "00" + i;
    } else if (i >= 10 && i < 100) {
      number = "0" + i;
    } else {
      number = i;
    }
    html += `<link rel="preload" href="${stylesheet_directory_uri}/media/frames/03/optim/scene-3-${number}.jpg" as="image">`;
  }
  document.querySelector("head").insertAdjacentHTML("beforeend", html);

  /* Scene 4 */
  html = "";
  for (let i = 0; i <= 299; i++) {
    let number;
    if (i < 10) {
      number = "00" + i;
    } else if (i >= 10 && i < 100) {
      number = "0" + i;
    } else {
      number = i;
    }
    html += `<link rel="preload" href="${stylesheet_directory_uri}/media/frames/04/optim/scene-4-${number}.jpg" as="image">`;
  }
  document.querySelector("head").insertAdjacentHTML("beforeend", html);
}

window.onload = () => {
  preloadRestOfScenes();
};