Jasper
Jasper

Reputation: 5238

Optimize jQuery events

I've a lot of checkboxes, like:

<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
...nearly 1000 

They can be placed in different places of the document.

Using jQuery I replace each checkbox with the following:

<div class="checkbox">
    <input type="checkbox">
</div>

This is needed for customization.

Then, I bind some events to the parent div and a checkbox, like:

input.on('keyup keydown keypress click', function(e) {
    ...
});

div.on('click mouseover mouseout', function(e) {
    ...
});

And I get a nearly 5 seconds freeze time on page load.

If I remove event bindings, everything works fine. So the tightest place here is events.

I've tried to use nearly this:

parent.on('keyup keydown keypress click', input, function(e) {
    ...
});

or 

$(document).on('keyup keydown keypress click', input, function(e) {
    ...
});

or

input.delegate('keyup keydown keypress click', function(e) {
    ...
});

...and some different ways of bindings

But none of them help (some are buggy and don't work as expected).

I've also read some articles about the event delegation, but don't have a reliable solution yet.

So the leak here is the number of events and bindings. 1000 elements = ~7000 event bindings and so on.

How can I optimize this code to work without the freeze time on page load?

Upvotes: 0

Views: 161

Answers (1)

n3rd
n3rd

Reputation: 6089

Have you tried "delegating it up" as much as possible, e.g.

$('body').on('keyup keydown keypress click', 'input', function (event) {
    // ...
});

If you're using jQuery < 1.7, use delegate instead:

$('body').delegate('input', 'keyup keydown keypress click', function (event) {
    // ...
});

Upvotes: 1

Related Questions