用于加载图像的预加载器

时间:2014-08-12 05:40:41

标签: javascript jquery animation svg

我目前正在研究SVG SMIL动画,我正在使用一些.png和.gif文件来简化我在IE中的动画。对于这个动画,我试图在动画之前获得Preloader并加载其他内容。

问题是我没有让Preloader正常工作。我的.html页面首先加载,然后预加载器开始...在Preloader中,我也使用了网上提供的几个预加载器。但它们对我没有帮助。

脚本和.html文件加载时间可以通过domContentLoaded计算,但是对于图像。我不知道该怎么做。如果有人可以建议我一个很棒的方式。

这是preloader.js的代码,我在网上找到了:

$(document).ready(function () {
"use strict"
//indexOf support for IE8 and below. 
if (!Array.prototype.indexOf){
  Array.prototype.indexOf = function(elt /*, from*/){
    var len = this.length >>> 0;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++){
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}

//bgImg for holding background images in the page & img array for images present in the document(<img src="">).
var bgImg = [], img = [], count=0, percentage = 0;

//Creating loader holder. 
$('<div id="loaderMask"><span>0%</span></div>').css({
    position:"fixed",
    top:0,
    bottom:0,
    left:0,
    right:0,
    background:'#fff'
}).appendTo('body');

//Using jQuery filter method we parse all elemnts in the page and adds background image url & images src into respective arrays.
$('*').filter(function() {

    var val = $(this).css('background-image').replace(/url\(/g,'').replace(/\)/,'').replace(/"/g,'');
    var imgVal = $(this).not('image').attr('xlink:href');

    //Getting urls of background images.
    if(val !== 'none' && !/linear-gradient/g.test(val) && bgImg.indexOf(val) === -1){
        bgImg.push(val)
    }

    //Getting src of images in the document.
    if(imgVal !== undefined && img.indexOf(imgVal) === -1){
        img.push(imgVal)
    }
});

//Merging both bg image array & img src array
var imgArray = bgImg.concat(img); 
console.log(imgArray.length);
//Adding events for all the images in the array.
$.each(imgArray, function(i,val){ 
    //Attaching load event 
    $("<image />").attr("xlink:href", val).bind("load", function () {
        console.log('val'+val);
        completeImageLoading();
    });

    //Attaching error event
    $("<image />").attr("xlink:href", val).bind("error", function () {
        imgError(this);
    });
})

//After each successful image load we will create percentage.
function completeImageLoading(){
    count++;
    percentage = Math.floor(count / imgArray.length * 100);
    console.log('percentage:'+percentage);
    $('#loaderMask').html('<span>'+percentage + '%'+'</span>');

    //When percentage is 100 we will remove loader and display page.
    if(percentage == 100){
        $('#loaderMask').html('<span>100%</span>')
        $('#loaderMask').fadeOut(function(){
            $('#loaderMask').remove()
        })
    }
}

//Error handling - When image fails to load we will remove the mask & shows the page. 
function imgError (arg) {
    $('#loaderMask').html("Image failed to load.. Loader quitting..").delay(3000).fadeOut(1000, function(){
        $('#loaderMask').remove();
    })
}

});

2 个答案:

答案 0 :(得分:1)

我开始执行我的js代码之前确保我或外部数据或图像被加载的一个小技巧是,我用display:none创建一个div并用我需要加载的所有标签填充它。

<body>

    <span id="loadingText">Loading...</span>

    <div style="display:none">
        <img src="pathtoimage1">
        <img src="pathtoimage2">
        <img src="pathtoimage3">
    </div>

    <script>
        window.onload = function(){
           //This gets called when all the items in that div has been loaded and cached.
           document.getElementById("loadingText").style.display = "none";
        }
    </script>

</body>

答案 1 :(得分:0)

我用它来预加载动画的图像。 您可以根据需要添加和删除加载的数量。

<script language="javascript">function preloader() {
    if (document.images) {
        var img1 = new Image();
        var img2 = new Image();
        var img3 = new Image();
        var img4 = new Image();
        var img5 = new Image();
        var img6 = new Image();
        var img7 = new Image();
        var img8 = new Image();
        var img9 = new Image();

        img1.src = "image link here";
        img2.src = "image link here";
        img3.src = "image link here";
        img4.src = "image link here";
        img5.src = "image link here";
        img6.src = "image link here";
        img7.src = "image link here";
        img8.src = "image link here";
        img9.src = "image link here";
    }
}
function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            if (oldonload) {
                oldonload();
            }
            func();
        }
    }
}
addLoadEvent(preloader);</script>