javascripthtmljquerycsspreloader

How To Disable Scrolling During Loading?


I'm working on my personal website and have implemented a preloader. After adding a second div to my website, I noticed I can scroll during the page loading. I dunno about you but I find that ugly and disturbing.

Here is a quick video. (I use chromeOS)

Video

I really couldn't find anything on this because I think I was the only one with this problem. I'm not sure, however.

I used $(window).on("load",function(){$(".loader-wrapper").fadeOut("slow");}); as well

Here is the code (Github Repo) Anyways, that's all I got.

Thanks in advance.


Solution

  • You can add by default a class to your body the class should be as follows.

    // CSS
    .no-scroll {
       overflow: hidden;
    }
    
    <body class="no-scroll">
    

    Once your script has completed or your function finishes you just call

    document.body.classList.remove('no-scroll');
    

    Make sure to add the following section at the end of your page.

    <script type="text/javascript">
    (function(){
       function onReady() {
         document.body.classList.remove('no-scroll');
       }
       
       if ( document.readyState === 'complete' ) {
          onReady();
       } else {
          document.addEventListener('DOMContentLoaded', onReady);
       }
    })();
    </script>
    

    Or you can do it with jQuery

    // Make sure this code is the last piece of code in your HTML.
    $(window).on("load", function() {
       document.body.classList.remove('no-scroll');
    });
    

    PS: Additionally to that consider the unlike scenario when someone does not have JavScript enabled so you add a default behavior. Take a look at <noscript> tag.