开发者

Showing a loading spinner only if the data has not been cached

Currently, my code shows a loading spinner gif, returns the data and caches it. However, once the data has been cached, there is a flicker of the loading gif for a split second before the data gets loaded in. It's distracting and I'd like to get rid of it. I think I'm using the wrong method in the beforeSend function here:

$.ajax({
                type    : "GET",
                cache   : false,
                url     : "book_data.php",
                data    : { keywords : keywords, page : page },
                beforeSend : function() {                   
                    $('.jPag-pages li:not(.cached)').each(function (i) {                        
                        $('#searchResults').html('<p id="loader">Loading...<img src="../assets/images/ajax-loader.gif" alt="Loading..." /></p>');
                    });
                },
                success : function(data) {  
                    $('.jPag-current').parent().addClass('cached');
                    $('#searchResults').replaceWith($(data).find('#searchResults')).find('table.sortable tbody tr:odd').addClass('odd');
                    detailPage();
     开发者_如何学JAVA               selectForm();                   
                }
            });

Edit:

Trying this from the comment, updated again with working code!

var timeout =  setTimeout(function(){ 
            $('#searchResults').html('<p id="loader">Loading...<img src="../assets/images/ajax-loader.gif" alt="Loading..." /></p>');
          }, 500 ); 
            $.ajax({
                type    : "GET",
                cache   : false,
                url     : "book_data.php",
                data    : { keywords : keywords, page : page },
                beforeSend : function() {   
                    timeout;
                },
                success : function(data) {  
                    clearTimeout(timeout);
                    $('.jPag-current').parent().addClass('cached');
                    $('#searchResults').replaceWith($(data).find('#searchResults')).find('table.sortable tbody tr:odd').addClass('odd');
                    detailPage();
                    selectForm();                   
                }
            });


You can delay showing the loading gif for a quarter of a second or so, enough so that it never shows if its loading from the cache.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜