user2726041
user2726041

Reputation: 359

jQuery ajax/load getting slower and slower

I am using the following function to load content into #canvas on click:

jQuery(document).ajaxComplete(function(){

    jQuery('.tabs a').on('click',function(e) {
        e.preventDefault();
        jQuery('.tabs a').removeClass('active');
        jQuery(this).addClass('active');
    });

    jQuery('#blog').on('click',function(e) {
        jQuery('#canvas').load('blog.php');
    });
    jQuery('#news').on('click',function(e) {
        jQuery('#canvas').load('news.php');
    });
    jQuery('#gallery').on('click',function(e) {
        jQuery('#canvas').load('gallery.php');
    });

});

HTML:

<ul class="tabs">
     <a id="blog">Blog</a>
     <a id="news">News</a>
     <a id="gallery">Gallery</a>
</ul>

<div id="canvas"></div>

This works fine when the tabs are clicked the first few times. However, the more times the tabs are clicked, the slower the content is loaded into #canvas. Eventually, the #canvas content starts to flick in and out between each page.

Any ideas what the problem might be?

I have tried replacing the load method with ajax and set caching to false, however the problem persists:

jQuery('#blog').on('click',function(e) {
    jQuery.ajax({
        url: 'blog.php',
        cache: false,
        success: function(result) {
            jQuery('#canvas').html(result);
        }
    });
});

Upvotes: 2

Views: 1569

Answers (1)

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93631

You are connecting event handlers inside the Ajax completion event, so each time you run an Ajax call you will have multiple event handlers attached to your elements. 1 then 2, then 3, then 4 handlers etc doing the same thing on each one. This unwanted repetition will eventually slow your page to a crawl.

Use delegated event handlers outside your Ajax call.

e.g.

jQuery(document).on('click', '.tabs a',function(e) {
    e.preventDefault();
    jQuery('.tabs a').removeClass('active');
    jQuery(this).addClass('active');
});

jQuery(document).on('click', '#blog', function(e) {
    jQuery('#canvas').load('blog.php');
});
jQuery(document).on('click', '#news', function(e) {
    jQuery('#canvas').load('news.php');
});
jQuery(document).on('click', '#gallery',function(e) {
    jQuery('#canvas').load('gallery.php');
});

You do not then need the jQuery(document).ajaxComplete(function(){ at all.

Delegated event handlers work by listening for an event (e.g. click) to bubble up to an ancestor element (document is the default if nothing else is closer/convenient). It then applies the jQuery selector at event time, so the item only needs to exists then. It then applies the event's callback function to only the matching elements that caused the event.

note: do not use body for delegated events as it has a serious bug.

Upvotes: 4

Related Questions