页面预加载器被困在一个循环中

时间:2017-06-26 14:21:29

标签: javascript jquery html css

所以我在我的网页上实现了预加载器,它可以工作!唯一的问题是主要内容出现,然后预加载器弹回,并且它无限循环!

我知道问题是什么,但我可以弄清楚我会怎么做。 <问题是

window.open("index.html", "_self");

这会不断重新加载索引页面,而索引页面会重新加载预加载器...任何帮助都会很棒!

HTML:

<body class="index-page">
<div id="overlay">
    <div class="preload-text">Loading. Please wait...</div>
    <div class="loader-frame">
        <div class="loader1"></div>
        <div class="loader2"></div>
    </div>
</div>
Body content below

JS:

$(document).ready(function(){

  var preload = document.getElementById("overlay")
  var loading = 0;
  var interval = setInterval(frame, 64);

  function frame() {
    if(loading == 100) {
      clearInterval(interval);
      window.open("index.html", "_self");
    } else {
      loading = loading + 1;
      if(loading == 90) {
        preload.style.animation = "fadeout 1s ease";
      }
    }
  }

});

CSS:

#overlay {
  height: 100%;
  width: 100%;
  background: #ffffff;
  position: fixed;
  left: 0;
  top0: 0;
  z-index: 9999;
}

.preload-text {
  width: 400px;
  height: 70px;
  margin: 150px auto 50px auto;
  font-size: 30px;
  text-align: center;
}

.loader-frame {
  width: 70px;
  height: 70px;
  margin: auto;
  position: relative;
}

.loader1, .loader2 {
  position: absolute;
  border: 5px solid transparent;
  border-radius: 50%;
}

.loader1 {
  width: 70px;
  height: 70px;
  border-top: 5px solid purple;
  border-bottom: 5px solid purple;
  animation: clockwisespin 2s linear 3;
}

.loader2 {
  width: 60px;
  height: 60px;
  border-left: 5px solid red;
  border-right: 5px solid red;
  top: 5px; left: 5px;
  animation: anticlockwisespin 2s linear 3;
}

@keyframes clockwisespin {
  from {transform: rotate(0deg);}
  to {transform: rotate(360deg);}
}

@keyframes anticlockwisespin {
  from {transform: rotate(0deg);}
  to {transform: rotate(-360deg);}
}

@keyframes fadeout {
  from {opacity: 1;}
  to {opacity: 0;}
}

1 个答案:

答案 0 :(得分:1)

$(document).ready(function(){

  var preload = document.getElementById("overlay")
  var loading = 0;
  var interval = setInterval(frame, 64);

  function frame() {
    if(loading == 100) {
      clearInterval(interval);
      $("#overlay").css('display', 'none');
    } else {
      loading = loading + 1;
      if(loading == 90) {
        preload.style.animation = "fadeout 1s ease";
      }
    }
  }

});

等待内容,这取决于内容的类型。对于图像,在js中创建DOM图像元素,而不将其放入文档中。然后在元素加载事件中,添加到一个计数器,当它已满时,您知道所有内容都已加载。 有点像:

var imagesToLoad = ["path/to/image/1", "path/to/image/2", ...];
var contentNotLoaded = imagesToLoad.length;

for(var i = 0; i < imagesToLoad.length; i++){
    var image = document.createElement("IMG");
    image.load = function(){
      contentLoaded++;
      if(contentNotLoaded == 0) $("#overlay").css('display', 'none');
    }
    image.src = imagesToLoad[i];
}

对于其他内容,它应该与.load事件一起工作,诀窍是在填充内容之前设置load事件(在图像中,分配src)