JavaScript-laadscherm terwijl pagina wordt geladen

Dit is een beetje moeilijk uit te leggen, dus ik zal mijn best doen

Dus terwijl een HTML-pagina wordt geladen, zou ik graag willen dat er een cool laadscherm aan de gang is. Als het laden klaar is, wil ik dat het laadscherm wordt gewist en dat het HTML-document wordt weergegeven.

Eigenlijk wil ik dit:

CSS:

/* Absolute Center CSS Spinner */
.loading {
  position: fixed;
  z-index: 999;
  height: 2em;
  width: 2em;
  overflow: show;
  margin: auto;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
}
/* Transparent Overlay */
.loading:before {
  content: '';
  display: block;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0,0,0,0.3);
}
/* :not(:required) hides these rules from IE9 and below */
.loading:not(:required) {
  /* hide "loading..." text */
  font: 0/0 a;
  color: transparent;
  text-shadow: none;
  background-color: transparent;
  border: 0;
}
.loading:not(:required):after {
  content: '';
  display: block;
  font-size: 10px;
  width: 1em;
  height: 1em;
  margin-top: -0.5em;
  -webkit-animation: spinner 1500ms infinite linear;
  -moz-animation: spinner 1500ms infinite linear;
  -ms-animation: spinner 1500ms infinite linear;
  -o-animation: spinner 1500ms infinite linear;
  animation: spinner 1500ms infinite linear;
  border-radius: 0.5em;
  -webkit-box-shadow: rgba(0, 0, 0, 0.75) 1.5em 0 0 0, rgba(0, 0, 0, 0.75) 1.1em 1.1em 0 0, rgba(0, 0, 0, 0.75) 0 1.5em 0 0, rgba(0, 0, 0, 0.75) -1.1em 1.1em 0 0, rgba(0, 0, 0, 0.5) -1.5em 0 0 0, rgba(0, 0, 0, 0.5) -1.1em -1.1em 0 0, rgba(0, 0, 0, 0.75) 0 -1.5em 0 0, rgba(0, 0, 0, 0.75) 1.1em -1.1em 0 0;
  box-shadow: rgba(0, 0, 0, 0.75) 1.5em 0 0 0, rgba(0, 0, 0, 0.75) 1.1em 1.1em 0 0, rgba(0, 0, 0, 0.75) 0 1.5em 0 0, rgba(0, 0, 0, 0.75) -1.1em 1.1em 0 0, rgba(0, 0, 0, 0.75) -1.5em 0 0 0, rgba(0, 0, 0, 0.75) -1.1em -1.1em 0 0, rgba(0, 0, 0, 0.75) 0 -1.5em 0 0, rgba(0, 0, 0, 0.75) 1.1em -1.1em 0 0;
}
/* Animation */
@-webkit-keyframes spinner {
  0% {
    -webkit-transform: rotate(0deg);
    -moz-transform: rotate(0deg);
    -ms-transform: rotate(0deg);
    -o-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(360deg);
    -moz-transform: rotate(360deg);
    -ms-transform: rotate(360deg);
    -o-transform: rotate(360deg);
    transform: rotate(360deg);
  }
}
@-moz-keyframes spinner {
  0% {
    -webkit-transform: rotate(0deg);
    -moz-transform: rotate(0deg);
    -ms-transform: rotate(0deg);
    -o-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(360deg);
    -moz-transform: rotate(360deg);
    -ms-transform: rotate(360deg);
    -o-transform: rotate(360deg);
    transform: rotate(360deg);
  }
}
@-o-keyframes spinner {
  0% {
    -webkit-transform: rotate(0deg);
    -moz-transform: rotate(0deg);
    -ms-transform: rotate(0deg);
    -o-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(360deg);
    -moz-transform: rotate(360deg);
    -ms-transform: rotate(360deg);
    -o-transform: rotate(360deg);
    transform: rotate(360deg);
  }
}
@keyframes spinner {
  0% {
    -webkit-transform: rotate(0deg);
    -moz-transform: rotate(0deg);
    -ms-transform: rotate(0deg);
    -o-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(360deg);
    -moz-transform: rotate(360deg);
    -ms-transform: rotate(360deg);
    -o-transform: rotate(360deg);
    transform: rotate(360deg);
  }
}

HTML:

<div class="loading">Loading&#8230;</div>

gebeurt terwijl de pagina wordt geladen. wanneer de pagina wordt geladen, wordt dat gewist en wordt de rest van het HTML-document weergegeven. (Ik ben een credits-systeem aan het maken en terwijl de credits worden geladen, heb ik het gewoon echt nodig om te zeggen dat het wordt geladen, mensen klagen dat ze nergens op kunnen klikken en ik moet ze allemaal vertellen dat het gewoon wordt geladen)

Ik wil graag zo veel mogelijk bij Ajax wegblijven omdat ik Javascript wil leren.


Antwoord 1, autoriteit 100%

Je kunt wachten tot het lichaam klaar is:

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>

Antwoord 2, autoriteit 12%

Maak aan het begin van uw laadscript uw

zichtbaar via css [display:block;] en maak de rest van de pagina onzichtbaar via css[display:none;].

Zodra het laden is voltooid, maakt u het laden onzichtbaar en de pagina weer zichtbaar met dezelfde techniek. U kunt de document.getElementById() gebruiken om de div’s te selecteren waarvan u de weergave wilt wijzigen.

Bewerken: zo zou het eruit zien. Wanneer de body klaar is met laden, zal het de javascript-functie aanroepen die de weergavewaarden van de verschillende elementen zal veranderen. Standaard zou uw stijl zijn om de pagina niet zichtbaar te hebben en het laden zichtbaar te maken.

<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>

Antwoord 3, autoriteit 4%

Om verder te bouwen op het ajax-gedeelte dat u wel of niet kunt gebruiken (uit de opmerkingen)

een eenvoudige manier om een andere pagina te laden en deze te vervangen door uw huidige 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>

Antwoord 4

Als je op je site ajax-oproepen hebt die gegevens laden, en dit is de reden dat de pagina traag laadt, is de beste oplossing die ik heb gevonden met

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

https://jsfiddle.net/44t5a8zm/– hier kun je wat ajax-aanroepen toevoegen en testen het.


Antwoord 5

Ik zou willen voorstellen om class no-jstoe te voegen aan je html om je CSS-kiezers eronder te nesten, zoals:

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

en wanneer u klaar bent met het laden van uw tegoedcode, verwijdert u deze:

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

Hiermee wordt uw laadspinner verborgen omdat er geen no-js-klasse in html is. Dit betekent dat u uw tegoedcode al heeft geladen


Antwoord 6

Deze methode gebruikt de WindowOrWorkerGlobalScope.setInterval(https:// developer.mozilla.org/en-US/doc)
methode om de gereedstatus van het document te volgen & kijk of het element <body>bestaat.

// 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)

Dit voorlaadscherm is gemaakt door Lapys @ https://github.com/LapysDev


Antwoord 7

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>

Antwoord 8

<html>
<div id="filter"></div>
<div id="load"></div>
<input type="button" value="Submit" onclick="myFunction()">
</html>
<style type="text/css">
*{
margin:0;
}
#load{
width:35px;
height:35px;
border-radius:50%;
border:2px solid #f3f3f3;
border-top:2px solid blue;
margin:auto;
right:0;
left:0;
top:40%;
position:fixed;
animation:load 1s linear infinite;
display:none;
}
@keyframes load{
0%{transform:rotate(0deg)}
100%{transform:rotate(360deg)}
}
#filter{
width:100%;
height:100%;
background:rgba(0, 0, 0, 0.5);
position:fixed;
display:none;
}
</style>
<script>
function myFunction(){
document.getElementById('filter').style.display="block";
document.getElementById('load').style.display="block";
window.location="location...";
}
</script>

Other episodes