开发者

jQuery: Wait for entire page--including ajax--to load?

开发者 https://www.devze.com 2022-12-20 06:30 出处:网络
I\'m using some jQuery tabs that load their content via ajax. I\'m using $(document).ready() in conjunction with the following code:

I'm using some jQuery tabs that load their content via ajax. I'm using $(document).ready() in conjunction with the following code:

// Hide loading animation, show content container
$("#content").show();
$("#loading").hide开发者_Go百科();

The purpose is to wait until the page is fully loaded, then show the content and hide the loading animation.

However, $(document).ready() only waits for the main page to load, not the external ajax content.

Is there something I can do wait until the ajax is loaded too?

Thanks in advance.


Depending on your ajax library, there is usually an option for supplying a callback which is called when the underlying ajax (get post..) operation is complete. You could use that callback to do your initialization rather than within .ready()....


First, if you wish to show animation while you're loading, use ajaxStart and ajaxStop. It does it auto-painlessly. Here's an example:

// Note! This uses jquery-ui to do the dialog...

jQuery(document).ready(function() {

    var body = jQuery("body");

    body.append('<div id="ajaxBusy"><div style="text-align:center" ><p>Communicating with server...<br \/>Please wait for this operation to finish.<br \/><img src="\/js\/jquery.smallhbar.indicator.gif" \/><\/p><\/div><\/div>');


  jQuery('#ajaxBusy').css({
    display:"none",
    margin:"0px",
    width:"260px",
    height:"170px",
    padding:"5px",
    textAlign:'center'
  });

  jQuery("#ajaxBusy").dialog({
    autoOpen: false,
    bgiframe: true,
    closeOnEscape: false,
    //modal: true,
    title: 'Shipping Department'});

  jQuery(document).ajaxStart(function() {
    jQuery('#ajaxBusy').dialog('open');
  });
  jQuery(document).ajaxStop(function() {
    jQuery('#ajaxBusy').dialog('close');
  });

});

With this code in my jQuery.ready section, a pretty dialog automatically flashes when ajax operations are occurring.

Finally, if you need to show content afterwards, you need to put your show() method within the success function of your ajax call. If you have multiple ajax calls happening, you'll need to use some variables as flags to signal when everything is done (clunky).

Do you have one or more than one ajax call happening?

0

精彩评论

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

关注公众号