Reputation: 97
I'm coding a site that will load all the content on a single page with jquery. Everything function works fine on itself, but when I begin to navigate, thus calling load functions one after the other, every instance is a bit slower, until the page completely crashes.
Is this a structural problem with ajax (i think not, but who knows?) or am I doing something wrong?
I sometimes have callback functions in the load function, but them also works fine.
EDIT
Ok, I was just wondering wether it was something common, but apparently it is not, so I'll show you some code:
// click and load part
$("#about").click(function(){
$("#c1").load('<?php echo get_site_url(); ?>/?page_id=5',
layout();
});
});
//callback function, basically some css injection
function layout() {
windowHeight = $(window).height();
$(".column-content").css('height',windowHeight-(containerTop+20)+'px');
$(".column-content_mode").css('height',windowHeight-(containerTop+60)+'px');
$(".container-column").css('height',windowHeight-(containerTop+20)+'px');
}
Everything is wrapped within a $(document).ready({ //all the js });
Thank you a lot for the quickness of your intervention.
Upvotes: 0
Views: 102
Reputation: 97
Allright, so. It turned out that the failure was caused by the js recursively loading itself. I did that by mistake because I wanted it to refresh each time an ajax event occurred.
Using $('#id').live('click', function(){...});
instead of $('#id').click(function(){...});
allowed me to refresh the js correctly and with no delay whatsoever.
Thanks everyone for your help!
Upvotes: 0
Reputation: 27227
Without looking at your code, I can tell you the most common cause for this problem:
$(function() {
$('#target').load('/your/url', function() {
$('.someclass').click(function() {
// Click handler for the new elements you just added
})
});
});
The problem here is that you are not only adding the handlers to the new elements that were just loaded, but you are also adding handlers to all of the existing elements on the page. It compounds exponentially!
To get around this, use the on
method to add the handlers once, and it'll automatically add them for new elements.
$(function() {
$('#target').on('click','.someclass',function() {
// Click handler for the new elements you will add in the future
});
$('#target').load('/your/url', function() {
// Nothing to do here now
});
});
Edit
$("#about").click(function(){
$("#c1").load('<?php echo get_site_url(); ?>/?page_id=5',
layout();
});
});
The second argument to load
should be a function reference. Get rid of the ()
there so you don't immediately call that function. You just want to pass the name, not execute it. Also, your }
is unmatched. Doublecheck it here.
Upvotes: 1