Reputation: 6272
We have a page layout as below, with jQuery click handler for a large number of HTML elements (thousands of DIVs).
The layout is like this:
The Navbar contains at least 2000+ DIVs and UL , LI (used for content navigation), and we have jQuery event handler bind to each element:
$('.navbar-item').click(function(){
/* click handler */
});
It took a lot of times to load, and on IE the performance is terrible !!! Is there anyway we can improve it ? or any alternative design to handle this problem ?
Upvotes: 0
Views: 394
Reputation: 3397
You have many possibilities to improve the performances
1.
You can load div just when user scroll and use Ajax
2.
use .on
and not .click
to add listener dynamically
For example, you can load some div
and check the scroll, use this function from James Padolsey, it works on all browsers
function getDocHeight() {
var D = document;
return Math.max(
Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
Math.max(D.body.clientHeight, D.documentElement.clientHeight)
);
}
$(window).scroll(function() {
// when the scroll is in bottom
if($(window).scrollTop() + $(window).height() == getDocHeight()) {
// use ajax to get more div
$.ajax({
url: "otherDivs.php", // page where you load div
data { firstDiv : '10', secondDiv : '20'}, // parameters : To load div 10 to 20
type: "POST"
})
.done(function( html ) {
$( "body" ).append( html ); // html contain div 10 to 20
});
}
});
It's just some ways to help you
Upvotes: 2
Reputation: 773
If the click handler is the same for more items instead of using:
$('.navbar-item').click(function(){
/* click handler */
});
you can make this:
var functionNav = function(){
/* click handler */
}
$('.navbar-item').on("click", functionNav)
If the functions are similar you can also parametrise a function to make more tasks.
Upvotes: 0
Reputation: 344
You can also use on function (http://api.jquery.com/on/)
for example:
$('div.navbar').on('click', '.navbar-item', function(){
/* click handler */
});
Upvotes: 2
Reputation: 57709
Reduce the number of nodes on the page. Load only what the user needs immediately, lazy load when the user scrolls down or opens a navigation level (in case you have a collapsible tree).
Upvotes: 1