在移动Safari上预加载HTML5应用的图片?

时间:2013-08-05 08:50:25

标签: javascript html5 mobile safari

是否可以为HTML5应用预先加载一组图片(定位到移动版Safari)?

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

我们尝试使用CSS背景属性并将每个图像作为单独的背景包含在内,但无法预先加载图像并保留启动图像。

这是我们用于设置启动图像的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'>

3 个答案:

答案 0 :(得分:0)

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

//修改

rajni的答案有一个很好的例子,说明应该做些什么。但是,您应该阅读有关.load()事件的警告on this page

答案 1 :(得分:0)

使用以下代码使用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>

答案 2 :(得分:0)

即使DOM尚未准备好,您也可以使用Image constructor预加载图像:

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
});