延迟使用jQuery显示Ajax加载gif的显示 [英] delay the showing of a ajax loading gif using jQuery

查看:102
本文介绍了延迟使用jQuery显示Ajax加载gif的显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

延迟显示ajax-loader gif的最佳方法是什么.当我单击一个按钮时,即使花费的时间只有几百毫秒,加载程序gif也会显示和隐藏,这给浏览器带来了一种闪烁.我要说的是,如果要花费超过1000毫秒才能完成ajax请求,则仅显示gif.

What is the best way to put a delay on the showing of a ajax-loader gif. When I click a button the loader gif shows and hides even if the time taken is a few hundred milli-seconds, this gives the browser a kind of flicker. What I want is to say only show the gif if it takes more than say 1000 milli-seconds to complete the ajax request.

 <script type="text/javascript">
     $(document).ready(function() {
         $('#loader').hide();
         $('#btnGetPeople').click(function() {
            $('#loader').show();
             $.getJSON("/User/GetName/10",
                null,
                function(data) { showPerson(data); });
         });
     });

     function showPerson(data) {
         alert(data);
         $('#loader').hide();
     }
</script>

我的加载程序div包含......

My loader div contains....

<div id="loader"><img alt="" src="/content/ajax-loader.gif" /></div>

实现此目标的最佳技术是什么?

What is the best technique to achieve this?

推荐答案

如您所见,我添加了一个超时,该延迟显示300ms.如果ajax更快,则在真正显示加载程序之前,将取消超时.

As you can see I added a timeout which delay showing for 300ms. If ajax is faster the timeout is cancelled before the loader gets really shown.

<script type="text/javascript">
    var showLoader;
    $(document).ready(function() {
        $('#loader').hide();
        $('#btnGetPeople').click(function() {
            // only show loader if ajax request lasts longer then 300 ms
            showLoader = setTimeout("$('#loader').show()", 300);
            $.getJSON("/User/GetName/10",
                null,
                function(data) { showPerson(data); });
        });
    });

    function showPerson(data) {
        clearTimeout(showLoader);
        alert(data);
        $('#loader').hide();
    }
</script>

这篇关于延迟使用jQuery显示Ajax加载gif的显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆