使用jQuery延迟显示ajax加载gif

什么是延迟显示ajax-loader gif的最佳方法。 当我点击按钮时,加载器gif显示并隐藏即使所花费的时间是几百毫秒,这也会给浏览器带来一种闪烁。 我想要的是只说显示gif,如果完成ajax请求需要超过1000毫秒。

 $(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(); }  

我的装载机div包含….

 

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

正如你所看到的,我添加了一个延迟,延迟显示为300毫秒。 如果ajax更快,则在加载器真正显示之前取消超时。

  

这是一种有趣的方式。 用这个替换$loader.show()

 $("#loader").data('timeout', window.setTimeout(function(){ $("#loader").show()}, 1000)); 

你的隐藏命令:

 window.clearTimeout($("#loader").hide().data('timeout')); 

你也可以这样做。

 var loadingTimer; $(document).ready(function () { $("#loader").ajaxStart(function () { loadingTimer = setTimeout(function () { $("#loader").show(); }, 200); }); $("#loader").ajaxStop(function () { clearTimeout(loadingTimer); $(this).hide(); }); } 

以为我会分享一些我为此所做的事情。 我有一种情况,我需要做的不仅仅是显示或隐藏一个元素。 所以我使用bind为加载器创建自定义事件:

 $("#loader").bind("delayshow", function (event, timeout) { var $self = $(this); $self.data('timeout', setTimeout(function () { // show the loader $self.show(); /* implement additional code here as needed */ }, timeout)); }).bind("delayhide", function (event) { // close and clear timeout var $self = $(this); clearTimeout($self.hide().data('timeout')); /* implement additional code here as needed */ }); // show it with a 500 millisecond delay $("#loader").trigger('delayshow', 500); // hide it $("#loader").trigger('delayhide');