Svelte document.readyState is behaving differently on Chrome and Firefox

131 Views Asked by At

I basically want a loading screen (a div element) to show for 2 seconds while the page is being loaded. I am using document.readyState for this and if it's completed loading everything then hide the loading screen else keep showing it.

The problem is, when I have this code, it works on Chrome but loads forever in Firefox (by loads forever I mean: it didn't hided that loader div, however the document was ready actually and I got to know this when I removed that loading div through Inspect tab and saw that everything has loaded just fine)

Now this code runs just fine in Chrome:

onMount(() => {
  const loader = <HTMLDivElement>document.getElementById('loader');
  if (document.readyState === 'complete') {
    setTimeout(() => {
      loader.style.visibility = 'hidden';
      console.log('loaded');
    }, 2000);
  }
});

But if I add document.onreadystatechange to it, now it works in Firefox but sadly now Chrome keeps loading forever as that loader.style.visibility = 'hidden' didn't fired:

document.onreadystatechange = () => {
  if (document.readyState === 'complete') {
    setTimeout(() => {
      loader.style.visibility = 'hidden';
      console.log('loaded');
    }, 2000);
  }
};

Why is this happening?

I tried console logging this:

document.onreadystatechange = () => {
  console.log("Hi");
};

This code doesn't even log anything on Chrome. But on Firefox it logs "Hi"

I guess it's a svelte thing as if you generally run this code inside a simple index.html's <script> tag then it works on both Chrome and Firefox but with svelte and onMount, this doesn't even fires...

1

There are 1 best solutions below

0
Abhay Salvi On

I resolved my issue as I just used onMount() on the parent component.

It executes the loader function only when all of its child components are loaded which is what onMount() does. I should have already placed onMount on the root component...

However I still am not very sure as to why browsers acted so differently.