JavaScript Loading Screen while page loads

后端 未结 6 1248
无人共我
无人共我 2020-11-30 18:17

This is a little hard to explain, So I\'ll try my best

So while a HTML page loads, I\'d like there to be a cool loading screen going on. When it finishes loading, I

相关标签:
6条回答
  • 2020-11-30 18:26

    If in your site you have ajax calls loading some data, and this is the reason the page is loading slow, the best solution I found is with

    $(document).ajaxStop(function(){
        alert("All AJAX requests completed");
    });
    

    https://jsfiddle.net/44t5a8zm/ - here you can add some ajax calls and test it.

    0 讨论(0)
  • 2020-11-30 18:27

    You can wait until the body is ready:

    function onReady(callback) {
      var intervalId = window.setInterval(function() {
        if (document.getElementsByTagName('body')[0] !== undefined) {
          window.clearInterval(intervalId);
          callback.call(this);
        }
      }, 1000);
    }
    
    function setVisible(selector, visible) {
      document.querySelector(selector).style.display = visible ? 'block' : 'none';
    }
    
    onReady(function() {
      setVisible('.page', true);
      setVisible('#loading', false);
    });
    body {
      background: #FFF url("https://i.imgur.com/KheAuef.png") top left repeat-x;
      font-family: 'Alex Brush', cursive !important;
    }
    
    .page    { display: none; padding: 0 0.5em; }
    .page h1 { font-size: 2em; line-height: 1em; margin-top: 1.1em; font-weight: bold; }
    .page p  { font-size: 1.5em; line-height: 1.275em; margin-top: 0.15em; }
    
    #loading {
      display: block;
      position: absolute;
      top: 0;
      left: 0;
      z-index: 100;
      width: 100vw;
      height: 100vh;
      background-color: rgba(192, 192, 192, 0.5);
      background-image: url("https://i.stack.imgur.com/MnyxU.gif");
      background-repeat: no-repeat;
      background-position: center;
    }
    <link href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css" rel="stylesheet"/>
    <link href="https://fonts.googleapis.com/css?family=Alex+Brush" rel="stylesheet">
    <div class="page">
      <h1>The standard Lorem Ipsum passage</h1>
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
        dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
    </div>
    <div id="loading"></div>

    Here is a JSFiddle that demonstrates this technique.

    0 讨论(0)
  • 2020-11-30 18:28

    I would suggest adding class no-js to your html to nest your CSS selectors under it like:

    .loading {
        display: none;
     }
    
    .no-js .loading {
     display: block;
     //....
    }
    

    and when you finish loading your credit code remove it:

    $('html').removeClass('no-js');
    

    This will hide your loading spinner as there's no no-js class in html it means you already loaded your credit code

    0 讨论(0)
  • 2020-11-30 18:32

    At the beginning of your loading script, just make your

    visible through css [display:block;] and make the rest of the page invisible through css[display:none;].

    Once the loading is done, just make the loading invisible and the page visible again with the same technique. You can use the document.getElementById() to select the divs you want to change the display.

    Edit: Here's what it would sort of look like. When the body finishes loading, it will call the javascript function that will change the display values of the different elements. By default, your style would be to have the page not visible the loading visible.

    <head>
        <style>
            #page{
                display: none;
            }
            #loading{
                display: block;
            }
        </style>
        <script>
            function myFunction()
            {
                document.getElementById("page").style.display = "block";
                document.getElementById("loading").style.display = "none";
            }
        </script>
    </head>
    
    <body onload="myFunction()">
        <div id="page">
    
        </div>
        <div id="loading">
    
        </div>
    </body>
    
    0 讨论(0)
  • 2020-11-30 18:42

    To build further upon the ajax part which you may or may not use (from the comments)

    a simple way to load another page and replace it with your current one is:

    <script>
        $(document).ready( function() {
            $.ajax({
                type: 'get',
                url: 'http://pageToLoad.from',
                success: function(response) {
                    // response = data which has been received and passed on to the 'success' function.
                    $('body').html(response);
                }
            });
        });
    <script>
    
    0 讨论(0)
  • 2020-11-30 18:50

    This method uses the WindowOrWorkerGlobalScope.setInterval(https://developer.mozilla.org/en-US/doc) method to track the ready states of the document & see if the <body> element exists.

    // Function > Loader Screen Script
    (function LoaderScreenScript(window = window, document = window.document, undefined = window.undefined || void 0) {
        // Initialization > (Processing Time, Condition, Timeout, Loader (...))
        let processingTime = 0,
            condition = function() {
                // Return
                return document.body
            },
            timeout = function() {
                // Return
                return (processingTime * 1e3) / 2
            },
            loaderScreenFontSize = typeof window.loaderScreenFontSize != 'undefined' ? window.loaderScreenFontSize : 14,
            loaderScreenMargin = typeof window.loaderScreenMargin != 'undefined' ? window.loaderScreenMargin : 10,
            loaderScreenMessage = typeof window.loaderScreenMessage != 'undefined' ? window.loaderScreenMessage : 'Loading, please wait&hellip;',
            loaderScreenOpacity = typeof window.loaderScreenOpacity != 'undefined' ? window.loaderScreenOpacity : .75,
            loaderScreenTransition = typeof window.loaderScreenTransition != 'undefined' ? window.loaderScreenTransition : .675,
            loaderScreenWidth = typeof window.loaderScreenWidth != 'undefined' ? window.loaderScreenWidth : 7.5;
    
        // Function > Update
        function update() {
            // Set Timeout
            setTimeout(function() {
                // Initialization > (Data, Metadata)
                var data = document.createElement('loader-screen-element'),
                    metadata = setInterval(function() {
                        /* Logic
                                [if:else if:else statement]
                        */
                        if (document.readyState == 'complete') {
                            // Alpha
                            alpha();
    
                            // Test
                            test()
                        }
                    });
    
                // Insertion
                document.body.appendChild(data);
    
                // Style > <body> > Overflow
                document.body.style = ('overflow: hidden !important; pointer-events: none !important; user-drag: none !important; user-select: none !important;' + (document.body.getAttribute('style') || ' ')).trim();
    
                // Modification > Data
                    // Inner HTML
                    data.innerHTML =
                        '<style media=all type=text/css>' +
                            'body::selection {' +
                                'background-color: transparent !important;' +
                                'text-shadow: none !important' +
                            '} ' +
                            '@keyframes rotate {' +
                                '0% { transform: rotate(0) }' +
                                'to { transform: rotate(360deg) }' +
                            '}' +
                        '</style>' +
                        "<div style='animation: rotate 1s ease-in-out 0s infinite backwards; border: " + loaderScreenWidth + "px solid rgba(0, 0, 0, " + loaderScreenOpacity + "); border-top-color: rgba(0, 51, 255, " + loaderScreenOpacity + "); border-radius: 50%; height: 75px; margin: 0 auto; margin-bottom: " + loaderScreenMargin + "px; width: 75px'> </div>" +
                        "<small style='color: rgba(127, 127, 127, .675); font-family: \"Open Sans\", \"Calibri Light\", Calibri, sans-serif; font-size: " + loaderScreenFontSize + "px !important; margin: 0 auto; margin-top: " + loaderScreenMargin + "px; text-align: center'> " + loaderScreenMessage + " </small>";
    
                    // Style
                    data.style = 'align-items: center; background-color: rgba(255, 255, 255, .98); display: flex; flex-direction: column; height: ' + innerHeight + 'px; justify-content: center; left: 0; margin: auto; max-height: 100% !important; max-width: 100% !important; min-height: 100vh; min-width: 100vh; position: fixed; top: 0; transition: ' + loaderScreenTransition + 's ease-in-out; width: ' + innerWidth + 'px; z-index: 2147483647';
    
                // Function
                    // Alpha
                    function alpha() {
                        // Clear Interval
                        clearInterval(metadata)
                    };
    
                    // Test
                    function test() {
                        // Style > Data
                            // Background Color
                            data.style.backgroundColor = 'transparent';
    
                            // Opacity
                            data.style.opacity = 0;
    
                        // Set Timeout
                        setTimeout(function() {
                            // Deletion
                            data.remove();
    
                            // Modification > <body> > Style
                            document.body.style = document.body.getAttribute('style').replace('overflow: hidden !important;', '').replace('pointer-events: none !important;', '').replace('user-drag: none !important;', '').replace('user-select: none !important;', '');
                            (document.body.getAttribute('style') || '').trim() || document.body.removeAttribute('style')
                        }, ((+getComputedStyle(data).getPropertyValue('animation-delay').replace(/[a-zA-Z]/g, '').trim() + +getComputedStyle(data).getPropertyValue('animation-duration').replace(/[a-zA-Z]/g, '').trim() + +getComputedStyle(data).getPropertyValue('transition-delay').replace(/[a-zA-Z]/g, '').trim() + +getComputedStyle(data).getPropertyValue('transition-duration').replace(/[a-zA-Z]/g, '').trim()) * 1e3) + 100);
                    }
            }, timeout())
        };
    
        /* Logic
                [if:else if:else statement]
        */
        if (condition())
            // Update
            update();
    
        else {
            // Initialization > Data
            var data = setInterval(function() {
                /* Logic
                        [if:else if:else statement]
                */
                if (condition()) {
                    // Update > Processing Time
                    processingTime += 1;
    
                    // Update
                    update();
    
                    // Metadata
                    metadata()
                }
            });
    
            // Function > Metadata
            function metadata() {
                // Clear Interval
                clearInterval(data);
    
                /* Logic
                        [if:else if:else statement]
    
                    > Deletion
                */
                if ('data' in window && typeof data == 'undefined')
                    delete window.data
            }
        }
    })(window, window.document, window.undefined || void 0)
    

    This pre-loading screen was made by Lapys @ https://github.com/LapysDev

    0 讨论(0)
提交回复
热议问题