在移动Safari上预加载HTML5应用程序的图像

Preload images for HTML5 app on mobile Safari?

本文关键字:HTML5 应用程序 图像 加载 移动 Safari      更新时间:2023-09-26

是否可以为HTML5应用程序预加载一组图像(针对移动Safari)?

在理想的情况下,应用程序的启动映像会一直存在,直到加载了某些映像为止。

我们尝试使用CSS background属性,并将每个图像作为单独的背景,但未能预加载图像并持久化启动图像。

这是我们用于设置启动图像的HTML,但在加载所有图像之前,这种情况无法持续:

<!-- iPhone 3 and 4 Non-Retina -->
<link rel='apple-touch-startup-image' media='(device-width: 320px)' href='/images/x/apple-touch-startup-image-320x460.png'>

使用以下代码使用jquery预加载图像。

<style type="text/css">
.start_up{width:100%;height:100%;position:fixed;z-index:999;display:none;}
.start_up img{width:100%;height:100%;display:block;}
</style>
<div class="start_up"> <img src="startup-image.png" /></div>
<script type="text/javascript">
$(document).ready(function(e) {
    //showing startup image. By default it will be display:none via css.
    $('.start_up').show();
    //load img
    var imgArray = ['image 1 path','image 2 path', 'image 3 path'];
    var total = imgArray.length;
    var imgLoaded = 0;
    for (var i in imgArray) {
        $("<img />").load(function() {
            imgLoaded++;
            if (imgLoaded == total) {
                //when all images loaded we hide start up image.
                $('.start_up').hide();
            }
        }).error(function() {
            imgLoaded++;
            if (imgLoaded == total) {
                //when all images loaded even error in img loading, we hide startup image.
                $('.start_up').hide();
            }   
        }).attr("src", imgArray[i]);
    }   
});
</script>

即使DOM还没有准备好,也可以使用Image构造函数来预加载图像:

var srcArray = ['/path/to/image1.jpg', '/path/to/image2.jpg']; // your image sources
function loadImages(srcArray, callback) {
  var loaded   = []; // here the loaded images will be contained
  for (var i; i < srcArray.length; i++) {
    // wrap the loop into a closure because onload is asynchronous
    (function(src) {
      // construct a new image
      var img = new Image();
      // use the onload event of the image
      // you can react to errors or load aborts using 'onerror' or 'onabort'
      img.onload = function() {
        loaded.push(img);
        // call the callback once all images are loaded
        loaded.length === srcArray.length && callback.call(this, loaded); 
      };
      // set the source
      img.src = src;
    })(srcArray[i]);
  }
}
// an easy, convenient function to load some images and do something
// when they are loaded
loadImages(srcArray, function(images) {
  // when this function is called, all images are loaded
  // use them as you please
});

您应该使用HTML显示"启动图像",并在$(document).ready事件中使用javascript添加其他图像。

//编辑

若尼的回答很好地说明了应该做什么。但是,您应该阅读本页上关于.load()事件的警告。