lennyklb
lennyklb

Reputation: 1367

Properly adjusting jQuery to support dynamic content

Not really sure how to address this, but here goes.

Say you can perform a procedure in jQuery when clicking button .btn:

$(document).ready(function(){
    $(".btn").click(function(){...});
});

This works on all .btn elements that were present when the document was ready. When we need to get this to work for dynamically loaded .btn elements, we need to address these elements through a static object that contains the dynamically loaded elements first, i.e. .static-container:

$(".static-container")
    .on("click", ".btn", function(){...});
});

However, any static element will do, not just the closest one to the element, meaning body as well, or a commonly used #page-wrapper or something like that.

I have a set of callbacks like this that I wish to include on multiple pages that may have different architectures, so I need some kind of container that appears on every page, which means I can be less specific.

My question is :

How much faster is it to be more specific (meaning: how much deeper in the DOM tree) when specifying a static container? What is good practice in this regard?

Upvotes: 0

Views: 35

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337714

The best practice is to use the closest possible static parent element to the dynamic content, i.e. as deep in the DOM tree as possible.

The result of this is that the event has fewer elements to bubble through, hence is handled faster. In real terms it's a difference of milliseconds, but who wouldn't want the fastest code possible.

Also note that it's important not to just put all delegated event handlers on a single root element (such as the document, body, or shared container) as this can lead to some slowdown if there are a multitude of event handlers on a single element. It's for this reason that live() was deprecated and removed several years ago.

Upvotes: 1

Related Questions