Gp90
Gp90

Reputation: 55

Loading progress bar doesn't work when loaded in a div

I'm using this code: jsbin; , in page.php and works well.

However, when in index.php I try to load page.php in a Div, script fails.

Index.php:

$('#myDiv').load('page.php');
.one {
  width:500px;
  height:400px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="myDiv" class="one"></div>

I've imported libraries, I've tryied to run script in Index.php and other stuff without result. Where I fail?

Upvotes: 2

Views: 253

Answers (1)

Ken Lee
Ken Lee

Reputation: 8073

I fixed your problem by:

  1. revising the "jsbin" javascript to the following

  function id(v){return document.getElementById(v); }
  function loadbar() {
    var ovrl = id("overlay"),
        prog = id("progress"),
        stat = id("progstat"),
        img = document.images,
        c = 0;
        tot = img.length;

    function imgLoaded(){
      c += 1;
      var perc = ((100/tot*c) << 0) +"%";
      prog.style.width = perc;
      stat.innerHTML = "Loading "+ perc;
      if(c===tot) return doneLoading();
    }
    function doneLoading(){
      ovrl.style.opacity = 0;
      setTimeout(function(){ 
        ovrl.style.display = "none";
      }, 1200);
    }
    for(var i=0; i<tot; i++) {
      var tImg     = new Image();
      tImg.onload  = imgLoaded;
      tImg.onerror = imgLoaded;
      tImg.src     = img[i].src;
    }    
  }


setTimeout(function(){ loadbar(); }, 3000);

and secondly, I changed your index file to :

<style>
.one {
  width:500px;
  height:400px;
}
</style>


<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
   
   $('#content').load("test1.html");
 
   
});
</script>
</head>
<body>

<div id="content" class="one"></div>

</body>
</html>



Actually you can see a live example here:

http://www.createchhk.com/20201028/test2.html (your index, modified as above)

http://www.createchhk.com/20201028/test1.html (your jsbin, modified as above)

The reason is:

  1. document.addEventListener('DOMContentLoaded', loadbar, false), which is in your original jsbin codes will be run immediately on pageload. But your index will not have the opportunity to trigger this "loadbar" function on load because the jquery will need time to load the jsbin into index

  2. I've added a delay (thru settimeout) otherwise the loader will disappear too soon --- before the actual page is loaded and displayed.

Upvotes: 1

Related Questions