【问题标题】:JavaScript Loading Screen while page loads页面加载时的 JavaScript 加载屏幕
【发布时间】:2014-10-04 21:05:02
【问题描述】:

这有点难以解释,所以我会尽力而为

所以当一个 HTML 页面加载时,我希望有一个很酷的加载屏幕。完成加载后,我希望清除加载屏幕并显示 HTML 文档。

基本上,我想要这个:

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>

在页面加载时发生。当页面加载时,它被清除,并显示 HTML 文档的其余部分。 (我正在制作一个积分系统,虽然积分加载我真的需要它说它正在加载,但人们抱怨他们无法点击任何东西,我必须告诉他们它只是在加载)

我想尽可能地远离 Ajax,因为我想学习 Javascript。

【问题讨论】:

  • 先加载“加载”屏幕怎么样?它可能会稍微减慢实际加载过程,但从心理学的角度来看,这将有很大帮助
  • @Rebirth 我可以,但是你的意思是喜欢有一个带有加载屏幕的页面,然后在 3 秒后重定向到真实页面吗?我可以这样做,但问题是,它并没有真正加载它,所以它看起来有点……幼稚。即使这样,我在 Jsfiddle 上运行它,我认为它不允许您在一个项目中制作多个页面。不过,我将通过将站点代码复制到我的计算机来尝试一下,看看它是如何工作的。
  • 我会说显示加载屏幕并使用 ajax 请求实际页面(对不起,我知道你想远离 ajax)。并在使用 success: 选项加载它时显示它。此外,即使它没有真正加载,最终用户也永远不会更聪明,因为技术已经告诉很多用户会有加载或启动过程。
  • @Rebirth 我想我将不得不解决 Ajax 或做假重定向的事情,直到出现新的东西。感谢您至少尝试提供帮助!

标签: javascript jquery html css loading


【解决方案1】:

你可以等到身体准备好:

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>

这是演示此技术的JSFiddle


更新

这是一个使用 Promise 的现代版本。承诺现在是完全可选的,因为它只用于延迟。页面加载后将触发DOMContentLoaded 事件。

const wait = (delay = 0) =>
  new Promise(resolve => setTimeout(resolve, delay));

const setVisible = (elementOrSelector, visible) => 
  (typeof elementOrSelector === 'string'
    ? document.querySelector(elementOrSelector)
    : elementOrSelector
  ).style.display = visible ? 'block' : 'none';

setVisible('.page', false);
setVisible('#loading', true);

document.addEventListener('DOMContentLoaded', () =>
  wait(1000).then(() => {
    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: flex;
  position: fixed;
  z-index: 100;
  width: 100%;
  height: 100%;
  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>

【讨论】:

  • 您可以调整时间间隔的超时,使其加载更快或更慢。
  • 谢谢。虽然它可能有点假,但它看起来确实很酷,并且会粘在一页上。非常感谢。我会试试看它是否有效。
  • 检查过了。看起来很酷!再次感谢您提供的所有帮助。
  • @MarkieJonesWTF 如果您想了解更多关于尺寸单位的信息,例如remvhvw,那么您应该查看A List Apart: Learning to Love the Boring Bits of CSS
  • 在你的小提琴中 - 加载屏幕如何旋转?没有找到任何关键帧、额外的资源或代码,可以实现这一点。魔法? :)
【解决方案2】:

在加载脚本的开头,只需将您的

通过 css [display:block;] 可见,并通过 css[display:none;] 使页面的其余部分不可见。

加载完成后,只需使用相同的技术使加载不可见并且页面再次可见。您可以使用 document.getElementById() 来选择要更改显示的 div。

编辑:这就是它的样子。当 body 完成加载时,它将调用 javascript 函数,该函数将更改不同元素的显示值。默认情况下,您的样式是使页面不可见,加载可见。

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

【讨论】:

  • 这似乎有点令人困惑,因为我是 Javascript 新手。 (而且我以前从未使用过 Ajax,所以不要告诉我使用它)你能解释一下关于 document.getElementById() 的更多信息并给我一个例子吗?
  • 嗯。每当我加载我的页面时,它就会完全空白,就像它没有加载一样,但 Firefox 说它有。
【解决方案3】:

进一步构建您可能使用或不使用的 ajax 部分(来自 cmets)

加载另一个页面并将其替换为当前页面的简单方法是:

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

【讨论】:

    【解决方案4】:

    如果在您的网站中有 ajax 调用加载一些数据,这就是页面加载缓慢的原因,我找到的最佳解决方案是使用

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

    https://jsfiddle.net/44t5a8zm/ - 在这里您可以添加一些 ajax 调用并进行测试。

    【讨论】:

      【解决方案5】:

      我建议将 no-js 类添加到您的 html 中,以便将您的 CSS 选择器嵌套在它下面,例如:

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

      当您完成加载信用代码后,将其删除:

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

      这将隐藏您的加载微调器,因为 html 中没有 no-js 类,这意味着您已经加载了您的信用代码

      【讨论】:

      • 它正在删除样式,但没有删除微调器的实际
      • 为什么需要删除
        ?加载另一个信用代码时,您可能需要再次显示它。在这种情况下,您只需将 no-js 类添加到 html $('html').addClass('no-js');,而无需再次重新创建微调器
      • 如果 div 没有被移除,它只会在字幕的底部显示“Loading....”,我不希望它像那样突出。
      • 您确定要从 html 中删除 no-js 类并将 .loading { display: none; } 添加到您的 CSS 中吗?
      【解决方案6】:

      此方法使用WindowOrWorkerGlobalScope.setInterval(https://developer.mozilla.org/en-US/doc) 方法来跟踪文档的就绪状态并查看&lt;body&gt; 元素是否存在。

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

      此预加载画面由 Lapys @https://github.com/LapysDev制作

      【讨论】:

        【解决方案7】:
        <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>
        

        【讨论】:

          猜你喜欢
          相关资源
          最近更新 更多
          热门标签