显示和隐藏加载gif的最佳实践

Best practice for display and hiding of loading gifs

本文关键字:最佳 gif 隐藏 加载 显示      更新时间:2023-09-26

我有一个页面,在其中单击一个按钮将另一个页面的内容加载到一个div中。我有一个加载gif,我想显示,当我点击按钮,当然,我想消失时,另一个页面的内容已经完全加载到div"maincontent"。下面是我目前的代码-这是实现这种效果的最佳实践-不知怎的,我认为一定有更好的方法来做到这一点?

index . php:

<html>
  <head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function() { 
        $('#loading').hide();
        $(document).on('click', '.menu1', function(){
          $('#loading').show();
          $('.maincontent').load("1.php");
        });
      });
    </script>
    <style>
      #loading {
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        position: fixed;
        display: block;
        opacity: 0.7;
        background-color: #fff;
        z-index: 99;
        text-align: center;
      }
      #loading-image {
        position: absolute;
        top: 25%;
        left: 50%;
        z-index: 100;
      }
    </style>
  </head>
  <body>
    <button class="menu1">Click</button>
    <div class="maincontent">
      <div id="loading">
        <img id="loading-image" src="images/ajax-loader.gif" alt="Loading..." />
      </div>
    </div>
  </body>
</html>

您可以使用.ajaxStart.ajaxStop事件分别显示和隐藏加载器。请检查下面的代码片段。

$(document).ready(function() { 
    $('#loading').hide().ajaxStart( function() {
        $(this).show();  // show Loading Div
    } ).ajaxStop ( function(){
        $(this).hide(); // hide loading div
    });
    $(document).on('click', '.menu1', function(){
      $('.maincontent').load("1.php");
    });
});