weixin_33749242 2017-11-14 09:27 采纳率: 0%
浏览 21

推迟ajax调用

I have a bit of js code on one of my pages that uses ajax to load some page elements. These happen at the very top of the page and unfortunately slow down loading of the rest of the page. I was wondering if there is a way to defer this so it loads after the page has loaded.

Here is the code I am using and it is located right before the closing body tag:

function countrySnippet() {
      $.ajax({
          url: '/country_snippets.php?sites=<?php echo json_encode($jam_sites); ?>&disabled=<?php echo json_encode($array_disabled); ?>&no_cat=<?php echo json_encode($category_disabled); ?>&hide=<?php echo $hide_overlay; ?>&use_id=<?php echo $use_id; ?>&snippet=<?php echo $display_country_snippet; ?>&title_top=<?php echo $snippet_title_top; ?>&title_bottom=<?php echo $snippet_title_bottom; ?>&theme=<?php echo $theme_detail['
          select_theme ']; ?>&code=<?php echo $country_code; ?>&region=<?php echo $country_region; ?>&thumbs=<?php echo $snippet_number_thumbs; ?>&size=<?php echo $settings_detail['
          index_thumbs_size ']; ?>',
          type: "get",
          beforeSend: function() {
            $('.ajax-load-snippet').show();
          }
        })
        .done(function(data) {
          $('.ajax-load-snippet').hide();
          $("#country-snippet").append(data).hide().fadeIn(1000);
        })
        .fail(function(jqXHR, ajaxOptions, thrownError) {
          $('.ajax-load-snippet').hide();
        });
    }
    countrySnippet();
  • 写回答

1条回答 默认 最新

  • 斗士狗 2017-11-14 10:51
    关注

    As suggested by @KamalSingh,

    $(document).ready(function() {
      function countrySnippet() {
        $.ajax({
            url: '/country_snippets.php?sites=<?php echo json_encode($jam_sites); ?>&disabled=<?php echo json_encode($array_disabled); ?>&no_cat=<?php echo json_encode($category_disabled); ?>&hide=<?php echo $hide_overlay; ?>&use_id=<?php echo $use_id; ?>&snippet=<?php echo $display_country_snippet; ?>&title_top=<?php echo $snippet_title_top; ?>&title_bottom=<?php echo $snippet_title_bottom; ?>&theme=<?php echo $theme_detail['
            select_theme ']; ?>&code=<?php echo $country_code; ?>&region=<?php echo $country_region; ?>&thumbs=<?php echo $snippet_number_thumbs; ?>&size=<?php echo $settings_detail['
            index_thumbs_size ']; ?>',
            type: "get",
            beforeSend: function() {
              $('.ajax-load-snippet').show();
            }
          })
          .done(function(data) {
            $('.ajax-load-snippet').hide();
            $("#country-snippet").append(data).hide().fadeIn(1000);
          })
          .fail(function(jqXHR, ajaxOptions, thrownError) {
            $('.ajax-load-snippet').hide();
          });
      }
      countrySnippet();
    });

    </div>
    
    评论

报告相同问题?