Last Updated: February 25, 2016
· edtheprogrammer

Don't use .live in jQuery

I recently came across this protip that suggests using .live in lieu of .ready in jQuery. I'm no jQuery guru, and I don't want to come off as a hater, but I have a couple problems with this.

First, .ready and .live serve two different purposes. It's not a direct apples to apples comparison. From the jQuery documentation .live is:

Attach an event handler for all elements which match the current selector, now and in the future.

and .ready is:

Specify a function to execute when the DOM is fully loaded.

Second, .live is deprecated. You should start using .on as per the jQuery documentation. There are a lot of issues with .live that are noted in the documentation, and is why it's been replaced with .on.

Third, I believe the point the author was trying to make was that your site will appear more responsive if you don't wait until the DOM is fully ready before attaching event handlers and such. He is correct, but only sometimes. Unless you have a specific reason not to you should always load your JavaScript at the end of your page. This alone will usually improve performance of your site. But it also negates the benefits of using .live. At this point most, if not all of the DOM is already loaded. So there isn't much to lose by waiting for .ready. Also, if you have your JavaScript at the end of your page and you use .live you are performing a selection on all matching elements in order to register your event. If you have lots of elements this can be a time consuming task. It's best to use .live (or, really .on) before DOM elements are added.

It would be better to say that you can potentially improve performance of your site if you are required to execute JavaScript before the rest of your page is loaded by registering events directly with .on instead of waiting until .ready fires before doing so.


Say Thanks

1 Response
Add your response


@rquinlivan Thanks for the comment. I certainly believe you should use on() where applicable, but it shouldn't be used as a simple replacement for ready(). Unless I’m mistaken, Even if your handler isn't manipulating the DOM the browser has to stop to download, parse, and execute your JavaScript before it can continue to load the rest of the DOM. Depending on your situation, you can actually degrade perceived performance by using on(). Obviously, if you need an event handler to be available before ready() fires then on() is the right choice. But, I think in many situations it’s best to load your JavaScript after everything else, and do stuff after the DOM is ready.

over 1 year ago ·