簡體   English   中英

在移動Safari上預加載HTML5應用的圖片?

[英]Preload images for HTML5 app on mobile Safari?

是否可以為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'>

您應該使用HTML顯示“啟動圖像”,並在$(document).ready事件中使用javascript添加其他圖像。

//編輯

rajni的答案很好地說明了應該做什么。 但是,您應該閱讀此頁面上有關.load()事件的警告。

使用以下代碼使用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
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM