programing

페이지 로드가 완료될 때까지 페이지 로드 div를 표시하는 방법은 무엇입니까?

javajsp 2023. 7. 23. 14:01

페이지 로드가 완료될 때까지 페이지 로드 div를 표시하는 방법은 무엇입니까?

우리 웹사이트에 집중적인 전화를 하기 때문에 로딩이 꽤 느립니다.

내가 어떻게 할 수 있는지 알기나 해?div페이지가 준비되는 동안 보여주기 위해 "로딩"과 유사한 말을 하고 모든 것이 준비되면 사라지는 것?

원답

저는 이것이 필요했고 몇 가지 조사 후에 이것을 생각해냈습니다(jQuery needed).

저먼 에, 직후에그.<body>태그 추가:

<div id="loading">
  <img id="loading-image" src="path/to/ajax-loader.gif" alt="Loading..." />
</div>

그런 다음 div 및 이미지의 스타일 클래스를 CSS에 추가합니다.

#loading {
  position: fixed;
  display: block;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  text-align: center;
  opacity: 0.7;
  background-color: #fff;
  z-index: 99;
}

#loading-image {
  position: absolute;
  top: 100px;
  left: 240px;
  z-index: 100;
}

다음, 이 의 페이지에 하세요. (에, 에, Javascript를 추가하세요.).</body>태그, 물론):

<script>
  $(window).load(function() {
    $('#loading').hide();
  });
</script>

하고 마막으로이위의치조정를고하지미드로지,background-color스타일 클래스와 함께 로드 디브의.

이게 다야, 잘 될 거예요.하지만 물론 당신은 그것을 가져야 합니다.ajax-loader.gif"base64 url"에 대해 base64 url을 합니다.srcvalue. 무료입니다. (우클릭 > 다른 이름으로 이미지 저장...)

갱신하다

jQuery 3.0 이상의 경우 다음을 사용할 수 있습니다.

<script>
  $(window).on('load', function () {
    $('#loading').hide();
  }) 
</script>

갱신하다

원래 답변은 jQuery 및 flexbox 시대 이전입니다.Angular, React 및 Vue.js와 같은 다양한 보기 관리 라이브러리/프레임워크를 사용할 수 있습니다.그리고 CSS의 경우 플렉스박스 옵션이 있습니다.다음은 CSS 대안입니다.

#loading {
  position: fixed;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  opacity: 0.7;
  background-color: #fff;
  z-index: 99;
}

#loading-image {
  z-index: 100;
}

이 스크립트는 페이지가 로드될 때 전체 창을 덮는 div를 추가합니다.CSS 전용 로딩 스피너가 자동으로 표시됩니다.창(문서가 아님)이 로드될 때까지 기다린 후 선택적으로 몇 초 더 기다립니다.

  • jQuery 3과 함께 작동(새 창 로드 이벤트가 있음)
  • 이미지가 필요하지 않지만 이미지를 쉽게 추가할 수 있습니다.
  • 추가 브랜딩 또는 지침에 대한 지연 변경
  • 종속성만 jQuery입니다.

https://projects.lukehaas.me/css-loaders 의 CSS 로더 코드

    
$('body').append('<div style="" id="loadingDiv"><div class="loader">Loading...</div></div>');
$(window).on('load', function(){
  setTimeout(removeLoader, 2000); //wait for page load PLUS two seconds.
});
function removeLoader(){
    $( "#loadingDiv" ).fadeOut(500, function() {
      // fadeOut complete. Remove the loading div
      $( "#loadingDiv" ).remove(); //makes page more lightweight 
  });  
}
        .loader,
        .loader:after {
            border-radius: 50%;
            width: 10em;
            height: 10em;
        }
        .loader {            
            margin: 60px auto;
            font-size: 10px;
            position: relative;
            text-indent: -9999em;
            border-top: 1.1em solid rgba(255, 255, 255, 0.2);
            border-right: 1.1em solid rgba(255, 255, 255, 0.2);
            border-bottom: 1.1em solid rgba(255, 255, 255, 0.2);
            border-left: 1.1em solid #ffffff;
            -webkit-transform: translateZ(0);
            -ms-transform: translateZ(0);
            transform: translateZ(0);
            -webkit-animation: load8 1.1s infinite linear;
            animation: load8 1.1s infinite linear;
        }
        @-webkit-keyframes load8 {
            0% {
                -webkit-transform: rotate(0deg);
                transform: rotate(0deg);
            }
            100% {
                -webkit-transform: rotate(360deg);
                transform: rotate(360deg);
            }
        }
        @keyframes load8 {
            0% {
                -webkit-transform: rotate(0deg);
                transform: rotate(0deg);
            }
            100% {
                -webkit-transform: rotate(360deg);
                transform: rotate(360deg);
            }
        }
        #loadingDiv {
            position:absolute;;
            top:0;
            left:0;
            width:100%;
            height:100%;
            background-color:#000;
        }
This script will add a div that covers the entire window as the page loads. It will show a CSS-only loading spinner automatically. It will wait until the window (not the document) finishes loading.

  <ul>
    <li>Works with jQuery 3, which has a new window load event</li>
    <li>No image needed but it's easy to add one</li>
    <li>Change the delay for branding or instructions</li>
    <li>Only dependency is jQuery.</li>
  </ul>

Place the script below at the bottom of the body.

CSS loader code from https://projects.lukehaas.me/css-loaders

<!-- Place the script below at the bottom of the body -->

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

window.onload = function(){ document.getElementById("loading").style.display = "none" }
#loading {width: 100%;height: 100%;top: 0px;left: 0px;position: fixed;display: block; z-index: 99}

#loading-image {position: absolute;top: 40%;left: 45%;z-index: 100} 
<div id="loading">
<img id="loading-image" src="img/loading.gif" alt="Loading..." />
</div>  

JS에서 생성된 가장 간단한 페이드아웃 효과가 있는 페이지 로드 영상:

저에게 완벽하게 효과가 있는 아래의 간단한 해결책이 하나 더 있습니다.

우선 아래와 같이 GIF 로딩과 함께 투명 오버레이인 Lockon class라는 이름의 CSS를 생성합니다.

.LockOn {
    display: block;
    visibility: visible;
    position: absolute;
    z-index: 999;
    top: 0px;
    left: 0px;
    width: 105%;
    height: 105%;
    background-color:white;
    vertical-align:bottom;
    padding-top: 20%; 
    filter: alpha(opacity=75); 
    opacity: 0.75; 
    font-size:large;
    color:blue;
    font-style:italic;
    font-weight:400;
    background-image: url("../Common/loadingGIF.gif");
    background-repeat: no-repeat;
    background-attachment: fixed;
    background-position: center;
}

이제 우리는 페이지가 로드될 때마다 전체 페이지를 오버레이로 포함하는 이 클래스로 우리의 div를 만들어야 합니다.

<div id="coverScreen"  class="LockOn">
</div>

이제 페이지가 준비될 때마다 이 표지 화면을 숨겨야 하며 페이지가 준비될 때까지 사용자가 이벤트를 클릭하거나 실행하지 못하도록 제한할 수 있습니다.

$(window).on('load', function () {
$("#coverScreen").hide();
});

위 솔루션은 페이지가 로드될 때마다 문제가 없습니다.

이제 문제는 페이지가 로드된 후에 버튼이나 시간이 오래 걸리는 이벤트를 클릭할 때마다 아래와 같이 클라이언트 클릭 이벤트에 이를 표시해야 합니다.

$("#ucNoteGrid_grdViewNotes_ctl01_btnPrint").click(function () {
$("#coverScreen").show();
});

즉, 이 인쇄 버튼을 클릭하면(보고서를 제공하는 데 오랜 시간이 소요됨) 결과를 제공하는 GIF가 포함된 커버 화면이 표시되고 페이지가 윈도우 위에 준비되면 로드 기능이 실행되고 화면이 완전히 로드되면 커버 화면이 숨겨집니다.

을 기본값으로 합니다.display:none그리고 나서 그것을 설정하는 이벤트 핸들러를 가지고 있습니다.display:block또는 완전히 적재된 후에 유사합니다.그럼 다음으로 설정된 디브를 가지세요.display:block"로딩"이 포함된 상태에서 다음으로 설정합니다.display:none이전과 동일한 이벤트 처리기에서.

사용하게 된 jQuery는 모든 Ajax 시작/중지를 모니터링하므로 각 Ajax 호출에 추가할 필요가 없습니다.

$(document).ajaxStart(function(){
    $("#loading").removeClass('hide');
}).ajaxStop(function(){
    $("#loading").addClass('hide');
});

컨테이너 CSS (에서) 및 로딩컨이너테 & 대대에및 CSS (mhyaaa답변서에의부분) 한hide 명령어:

#loading {
   width: 100%;
   height: 100%;
   top: 0px;
   left: 0px;
   position: fixed;
   display: block;
   opacity: 0.7;
   background-color: #fff;
   z-index: 99;
   text-align: center;
}

#loading-content {
  position: absolute;
  top: 50%;
  left: 50%;
  text-align: center;
  z-index: 100;
}

.hide{
  display: none;
}

HTML:

<div id="loading" class="hide">
  <div id="loading-content">
    Loading...
  </div>
</div>

이는 주로 '집중적인 통화'에 필요한 요소를 어떻게 로드하느냐에 따라 달라집니다. 처음에는 Ajax를 통해 로드하는 것이라고 생각했습니다.그런 경우 '보내기 전' 옵션을 사용하여 다음과 같은 Ajax 전화를 걸 수 있습니다.

$.ajax({
  type: 'GET',
  url: "some.php",
  data: "name=John&location=Boston",

  beforeSend: function(xhr){           <---- use this option here
     $('.select_element_you_want_to_load_into').html('Loading...');
  },

  success: function(msg){
     $('.select_element_you_want_to_load_into').html(msg);
  }
});

EDIT, 그 경우에, 나는 그 중 하나를 사용하는 것을 압니다.'display:block'/'display:none'은 위의옵관여와 함께 됩니다.$(document).ready(...)jQuery에서 하는 것이 아마도 가는 길일 것입니다.$(document).ready()함수는 실행하기 전에 전체 문서 구조가 로드되기를 기다립니다(그러나 모든 미디어가 로드되기를 기다리지는 않습니다).다음과 같은 작업을 수행할 수 있습니다.

$(document).ready( function() {
  $('table#with_slow_data').show();
  $('div#loading image or text').hide();
});

제 블로그는 100% 작동할 것입니다.

function showLoader()
{
    $(".loader").fadeIn("slow");
}
function hideLoader()
{
    $(".loader").fadeOut("slow");
}
.loader {
    position: fixed;
    left: 0px;
    top: 0px;
    width: 100%;
    height: 100%;
    z-index: 9999;
    background: url('pageLoader2.gif') 50% 50% no-repeat rgb(249,249,249);
    opacity: .8;
}
<div class="loader"></div>

성을 합니다.<div>로드 메시지를 포함하는 요소를 제공합니다.<div>한 후 되면 ID를 .<div>:

$("#myElement").css("display", "none");

...또는 일반 JavaScript:

document.getElementById("myElement").style.display = "none";

이것은 api 호출과 동기화됩니다. api 호출이 트리거되면 로더가 표시됩니다.api 호출이 성공하면 로더가 제거됩니다.페이지 로드 또는 API 호출 중에 사용할 수 있습니다.

  $.ajax({
    type: 'GET',
    url: url,
    async: true,
    dataType: 'json',
    beforeSend: function (xhr) {
      $( "<div class='loader' id='searching-loader'></div>").appendTo("#table-playlist-section");
      $("html, body").animate( { scrollTop: $(document).height() }, 100);
    },
    success: function (jsonOptions) {
      $('#searching-loader').remove();
      .
      .
    }
  });

CSS

.loader {
  border: 2px solid #f3f3f3;
  border-radius: 50%;
  border-top: 2px solid #3498db;
  width: 30px;
  height: 30px;
  margin: auto;
  -webkit-animation: spin 2s linear infinite; /* Safari */
  animation: spin 2s linear infinite;
  margin-top: 35px;
  margin-bottom: -35px;
}

/* Safari */
@-webkit-keyframes spin {
  0% { -webkit-transform: rotate(0deg); }
  100% { -webkit-transform: rotate(360deg); }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

당신의 테마 custom_drupal에 있는 drupal을 위하여.테마 파일

function custom_theme_preprocess_html(&$variables) {
$variables['preloader'] = 1;
}

본문의 기본 내용 링크를 건너뛰면 html.twig 파일에서

{% if preloader %} 
  <div id="test-preloader" >
    <div id="preloader-inner" class="cssload-container">
      <div class="wait-text">{{ 'Please wait...'|t }} </div> 
      <div class="cssload-item cssload-moon"></div>
    </div>
  </div>
{% endif %}  

CSS 파일로

#test-preloader {
position: fixed;
background: white;
width: 100%;
height: 100%;
top: 0;
left: 0;
z-index: 9999;
}
.cssload-container .wait-text {
text-align: center;
padding-bottom: 15px;
color: #000;
}

.cssload-container .cssload-item {
 margin: auto;
 position: absolute;
 top: 0;
 right: 0;
 bottom: 0;
 left: 0;
 width: 131px;
 height: 131px;
 background-color: #fff;
 box-sizing: border-box;
 -o-box-sizing: border-box;
 -ms-box-sizing: border-box;
 -webkit-box-sizing: border-box;
 -moz-box-sizing: border-box;
 box-shadow: 0 0 21px 3px rgba(130, 130, 130, 0.26);
 -o-box-shadow: 0 0 21px 3px rgba(130, 130, 130, 0.26);
 -ms-box-shadow: 0 0 21px 3px rgba(130, 130, 130, 0.26);
 -webkit-box-shadow: 0 0 21px 3px rgba(130, 130, 130, 0.26);
 -moz-box-shadow: 0 0 21px 3px rgba(130, 130, 130, 0.26);
 }

.cssload-container .cssload-moon {
border-bottom: 26px solid #008AFA;
border-radius: 50%;
-o-border-radius: 50%;
-ms-border-radius: 50%;
-webkit-border-radius: 50%;
-moz-border-radius: 50%;
animation: spin 1.45s ease infinite;
-o-animation: spin 1.45s ease infinite;
-ms-animation: spin 1.45s ease infinite;
-webkit-animation: spin 1.45s ease infinite;
-moz-animation: spin 1.45s ease infinite;
 }

여기 나열된 솔루션의 일부를 재사용하여 구현한 스플래시 화면이 필요했습니다.완전한 하위 호환성을 위해 Vanilla JS를 사용합니다.

1단계: 페이지 위에 스피너 gif가 있는 배경을 추가한 다음 모든 것이 로드되면 제거합니다.

body.has-js::before {
  content: '';
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  z-index: 10;
  height: 100vh;
  width: 100vw;
  pointer-events: none;
  transition: all .2s;
  background: white url('/img/spinner.gif') no-repeat center center / 50px;
}
body.loaded::before {
  opacity: 0;
  width: 0;
  height: 0;
}

2단계: 본체 태그 열기 직후에 작은 스크립트를 추가하여 로드/플래시 화면 표시를 시작합니다.

<body>
  <script>
    // Only show loader if JS is available
    document.body.className += ' has-js';
    // Option 1: Hide loader when 'load' event fires
    window.onload = function() { document.body.className += ' loaded'; }
    // Option 2: Hide loader after 2 seconds, in case the 'load' event never fires
    setTimeout(function(){ document.body.className += ' loaded'; }, 1000 * 2);
  </script>
  <!-- Page content goes after this -->
</body>

@mehyaa 답변을 기반으로 하지만 훨씬 더 짧습니다.

HTML(직후)<body>):

<img id = "loading" src = "loading.gif" alt = "Loading indicator">

CSS:

#loading {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 32px;
  height: 32px;
  /* 1/2 of the height and width of the actual gif */
  margin: -16px 0 0 -16px;
  z-index: 100;
  }

Javascript (jQuery, 이미 사용하고 있기 때문에):

$(window).load(function() {
  $('#loading').remove();
  });

언급URL : https://stackoverflow.com/questions/1853662/how-to-show-page-loading-div-until-the-page-has-finished-loading