1

I have a large page where the DOM takes a while to completely load. I thought it would be good to have a little loading animation appear whilst the page is loading so I implemented this:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="https://github.com/Modernizr/Modernizr/raw/master/modernizr.js"></script>
    <script>
        // Wait for window load
        $(window).load(function() {
            // Animate loader off screen
            $("#wait").animate({
                top: -200
            }, 1500);
        });
    </script>

<body>
<div id="wait">
<img src="/assets/images/ajax-loader.gif" />
</div>

(found here)

It works but only at the very last moment, when the DOM is about 4/5ths already loaded. Was hoping if anyone knew a better way to do this?

4

1 回答 1

1

不使用 $(window).load() 尝试 $(document).ready(),通常在加载大图像时通常使用 $(window).load()

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="https://github.com/Modernizr/Modernizr/raw/master/modernizr.js"></script>
    <script>
        // Wait for window load
        $(document).ready(function() {
            // Animate loader off screen
            $("#wait").animate({
                top: -200
            }, 1500);
        });
    </script>

<body>
<div id="wait">
<img src="/assets/images/ajax-loader.gif" />
</div>

编辑 如果你加载一个大图像我修改了代码,希望这会对你有所帮助

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
function showLoading(){
  var $loading = $(".loading");
  var windowH = $(window).height();
  var windowW = $(window).width();

  $loading.css({
    position:"fixed",
    left: ((windowW - $loading.outerWidth())/2 + $(document).scrollLeft()),
    top: ((windowH - $loading.outerHeight())/2 + $(document).scrollTop())
  }).show();
}

function hideLoading(){
   $(".loading").hide();
}

 $(function(){
      showLoading();

      $("#Iframe").load(function(){
        hideLoading();
      }).attr("src", "http://www.somesite.com/images/Purple-Flowers-Wallpaper.jpg");

    });
</script>

<div id="dialog-box">
    <iframe id="Iframe"  src="javascript:void(0);" height="500px" width="800px" ></iframe>
    </div>

<div class="loading">
      <br /><br />
      <div>Loading...</div>
    </div> 
于 2012-06-28T04:38:15.183 回答