Speed up your jQuery by Replacing .live() with .on()

Posted on December 11th, 2011 in category: Tips and Tricks

The live() is really practical since you don’t need to reattach it when adding new objects and since that it’s also widely used. But it’s not very efficient and has a few issues. Two new functions where added to jQuery 1.7 to replace the live() function, they are the on() and the off() functions. As you can image they on() function adds an event handler and the off() function removes it.

One issue with the live event is that it will always look through the entire document, even if you’re only interested to catch events inside a certain element. With the on() event you can specify the area you wish to handle events in, like this:

<html>
	<head>
		<script>
			$('#container').on('click', 'a', function() {
				alert('HI!');
			});
		</script>
	</head>
	<body>
		<a href="#">Some other link</a>
		<div id="container">
			<a href="#">Say hi!</a>
		</div>
	</body>
</html> 

The code above will show an alert when clicking a link inside the container div but not on events outside.

More information

You can check out the performance increase and write your own tests here: http://jsperf.com/live-vs-on

This was just just a short tip, if you want more information about the events check out this very informative article.

Comments

  • zap, August 1st, 2012

    dude, you’re missing the script tag in the head section…

  • lasse, August 4th, 2012

    Nice find zap, it’s corrected now, thanks.

Trackbacks

No trackbacks are posted.

× 4 = twenty eight