Home > Enterprise >  Why is my website showing a loading icon when every file has loaded successfully?
Why is my website showing a loading icon when every file has loaded successfully?

Time:10-07

So I was learning JavaScript Promises and created a webpage that shows text derived from another file on the directory. It successfully loads the site and everything, but the problem is that even after the site loading and accessing the data from the other webpage, it is showing the loading icon. I tried removing the promise from the file, and when I visited the webpage again, there was no loading icon. So I think there is something wrong with the promise.

  • 1. controller.js(The Main JS File)
function myDisplayer(some) {
  document.write(some);
}
async function loadController(){
    let myPromise = new Promise(function(myResolve, myReject) {
      let req = new XMLHttpRequest();
      req.open('GET', "controllerDummy.html");
      req.onload = function() {
        if (req.status == 200) {
          myResolve(req.response);
        } else {
          myReject("File not Found");
        }
      };
      req.send();
    });
    myDisplayer(await myPromise);
}

loadController()
  • 2. controller.html(The Main File)
<!DOCTYPE html>
<html style="background-color: black;">
<head>
    <script type="text/javascript" src="controller.js"></script>
</head>
<body>
    
</body>
</html>
  • 3. controllerDummy.html(The Dummy File from which the promise extracts the response text)
<!DOCTYPE html>
<html style="background-color: black;">
    <body>Loading Controller</body>
</html>

These are all the files, and now the screenshot(s).The webpage, the derived text is black and the bg is black too because I do not like white-colored websites and white UI design

As you can see, the promise has loaded, but the site is still loading with the icon. Is there any fix to this? Is this way outdated or something?

CodePudding user response:

fulfill the promise

function myDisplayer(some) {
  document.write(some);
}
async function loadController(){
    let myPromise = new Promise(function(myResolve, myReject) {
      let req = new XMLHttpRequest();
      req.open('GET', "controllerDummy.html");
      req.onload = function() {
        if (req.status == 200) {
          myResolve(req.response);
        } else {
          myReject("File not Found");
        }
      };
      req.send();
    });
    
    myPromise.then((result)=>{
      myDisplayer(result);
    }).catch((error)=>{
      //handle error
    });
    
}

loadController()

  • Related