开发者

jQuery - Why does this code work in step through, but not in real time (show spinner, followed by load)

开发者 https://www.devze.com 2022-12-21 08:52 出处:网络
Why do I not see the spinner image when I run this code? However when I debug through it using firebug I do see the text/spinner image at the beginning:

Why do I not see the spinner image when I run this code? However when I debug through it using firebug I do see the text/spinner image at the beginning:

<div id="spinner">
  <img src="/images/ajax-loader.gif"/>
  Text
</div>

<div id="events">
</div>

<script type="text/javascript" cha开发者_JS百科rset="utf-8">

 function load_events() {
   $("#events").load("robots.txt");
 }

 $(document).ready(function(){
   $("#spinner").show()
   $("#events").hide()

   setTimeout("load_events()",2000);
   $("#events").show()
   $("#spinner").hide()

 });

</script>

thanks

PS. In particular I need it so the spinner will keep showing until the AJAX response from the "load" actually all comes back (not until the load event itself starts, as the API I'm calling then still takes a couple of seconds before it comes back with the content)

PSS. Latest code I'm using after feedback. Still suffers from issue noted in the PS above.

<div id="spinner"> <img src="/images/ajax-loader.gif"/> </div>

<div id="events"> </div>

<script type="text/javascript" charset="utf-8">

 $(document).ready(function(){
   $("#spinner").show();
   $("#events").hide();

   setTimeout(function(){
     $("#events").load("weekends/concerts_display");
     $("#events").show();
     $("#spinner").hide();
   },10);

 });

</script>


The lines of code after the timeout run immediately, consider using something like this:

$(document).ready(function(){
    $("#spinner").show();
    $("#events").hide();

    setTimeout(function(){
        $("#events").load("robots.txt", null, function(){
            $("#events").show();
            $("#spinner").hide();
        });
    },2000);
});


You might also consider using jQuery's ajaxStart and ajaxStop methods for showing and hiding your gif, rather than a setTimeout. The nice thing about doing it this way is that it should kick in for any ajax on the page, so you can program it once and forget it.

$('body').ajaxStart(function(){
  $('#spinner').show();
});
$('body').ajaxStop(function(){
  $('#spinner').hide();
});


setTimeout(load_events,2000);

Note that here you send a function, not a string.

You use also a unnamed function:

setTimeout(function(){
    $("#events").load("robots.txt");
},2000);
0

精彩评论

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

关注公众号