Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Learning jQuery - Fourth Edition

You're reading from   Learning jQuery - Fourth Edition Add to your current website development skills with this brilliant guide to JQuery. This step by step course needs little prior JavaScript knowledge so is suitable for beginners and more seasoned developers alike.

Arrow left icon
Product type Paperback
Published in Jun 2013
Publisher Packt
ISBN-13 9781782163145
Length 444 pages
Edition 4th Edition
Languages
Tools
Arrow right icon
Toc

Table of Contents (24) Chapters Close

Learning jQuery Fourth Edition
Credits
Foreword
About the Authors
About the Reviewers
www.PacktPub.com
Preface
1. Getting Started FREE CHAPTER 2. Selecting Elements 3. Handling Events 4. Styling and Animating 5. Manipulating the DOM 6. Sending Data with Ajax 7. Using Plugins 8. Developing Plugins 9. Advanced Selectors and Traversing 10. Advanced Events 11. Advanced Effects 12. Advanced DOM Manipulation 13. Advanced Ajax JavaScript Closures Testing JavaScript with QUnit Quick Reference Index

Handling memory-leak hazards


JavaScript manages its memory using a technique known as garbage collection. This is in contrast to low-level languages such as C, which require programmers to explicitly reserve blocks of memory and free them when they are no longer being used. Other languages such as Objective-C assist the programmer by implementing a reference-counting system, which allows the user to note how many pieces of the program are using a particular piece of memory so it can be cleaned up when no longer used. JavaScript is a high-level language, on the other hand, and generally takes care of this bookkeeping behind the scenes.

Whenever a new memory-resident item such as an object or function comes into being in JavaScript code, a chunk of memory is set aside for this item. As the object gets passed around to functions and assigned to variables, more pieces of code begin to point to the object. JavaScript keeps track of these pointers, and when the last one is gone, the memory taken by the object is released. Consider a chain of pointers:

Here, object A has a property that points to B and B has a property that points to C. Even if object A here is the only one that is a variable in the current scope, all three objects must remain in memory because of the pointers to them. When A goes out of scope, however (such as at the end of the function it was declared in), then it can be released by the garbage collector. Now B has nothing pointing to it, so it can be released, and finally C can be released as well.

More complicated arrangements of references can be harder to deal with:

Now we've added a property to object C that refers back to B. In this case, when A is released, B still has a pointer to it from C. This reference loop needs to be handled specially by JavaScript, which must notice that the entire loop is isolated from the variables that are in scope.

Avoiding accidental reference loops

Closures can cause reference loops to be inadvertently created. Since functions are objects that must be kept in memory, any variables they have in their closing environment are also kept in memory. Consider the following code:

function outerFn() {
  var outerVar = {};
  function innerFn() {
    console.log(outerVar);
  }
  outerVar.fn = innerFn;
  return innerFn;
};

Listing A.20

Here, an object called outerVar is created and referenced from within the inner function innerFn(). Then, a property of outerVar that points to innerFn() is created and innerFn() is returned. This creates a closure on innerFn() that refers to outerVar, which in turn refers back to innerFn().

Scenarios such as this can keep variables in memory longer than desired, but are fairly easy to notice. Sometimes, though, the loop can be even more insidious than this:

function outerFn() {
  var outerVar = {};
  function innerFn() {
    console.log('hello');
  }
  outerVar.fn = innerFn;
  return innerFn;
};

Listing A.21

Here, we've changed innerFn() so that it no longer refers to outerVar. However, this does not break the loop! Even though outerVar is never referred to from innerFn(), it is still in the closing environment of innerFn(). All variables in the scope of outerFn() are implicitly referred to by innerFn() due to the closure. So, closures make it easy to accidentally create these loops.

Managing loops between the DOM and JavaScript

All of this is generally not an issue because JavaScript is able to detect these loops and clean them up when they become orphaned. Older versions of Internet Explorer, however, have difficulty handling one particular class of reference loops. When a loop contains both DOM elements and regular JavaScript objects, Internet Explorer cannot release either one because they are handled by different memory managers. These loops are never freed until the browser is closed, which can eat up a great deal of memory over time. A common cause of such a loop is a simple event handler:

$(document).ready(function() {
  var button = document.getElementById('button-1');
  button.onclick = function() {
    console.log('hello');
    return false;
  };
});

Listing A.22

When the click handler is assigned, this creates a closure with button in the closing environment. But button now contains a reference back to the closure—the onclick property itself. Thus, the resulting loop can't be released by Internet Explorer even when we navigate away from the page.

To release the memory, we'd need to break the loop, such as by getting rid of the onclick property before the window is closed (taking care not to introduce a new loop between the window and its onunload hander). Alternatively, we could rewrite the code to avoid the closure:

function hello() {
  console.log('hello');
  return false;
}
$(document).ready(function() {
  var button = document.getElementById('button-1');
  button.onclick = hello;
});

Listing A.23

Since the hello() function no longer closes over button, the reference only goes one way (from button to hello) and there is no loop, and therefore no memory leak.

Disentangling reference loops with jQuery

Now let's write the same code, but using normal jQuery constructs:

$(document).ready(function() {
  var $button = $('#button-1');
  $button.click(function(event) {
    event.preventDefault();
    console.log('hello');
  });
});

Listing A.24

Even though a closure is still created causing the same kind of loop as before, we do not get an IE memory leak from this code. Fortunately for us, jQuery is aware of the potential leaks and manually releases all the event handlers that it assigns. As long as we faithfully adhere to using jQuery's event-binding methods for our handlers, we need not fear leaks caused by this particular common idiom.

This doesn't mean we're completely out of the woods. We must continue to take care when we're performing other tasks with DOM elements. Attaching JavaScript objects to DOM elements can still cause memory leaks in older Internet Explorer versions; jQuery just helps make this situation far less prevalent.

Because of this, jQuery gives us another tool to help avoid these leaks. In Chapter 12, Advanced DOM Manipulation, we saw that the .data() method allows us to attach information to DOM elements in much the same way as we can with expando properties. Since this data is not stored directly as an expando (jQuery uses an internal map to store the data using IDs it creates), the reference loop is never formed and we sidestep the memory leak issue. Whenever an expando seems like a convenient data storage mechanism, we should consider .data() a safer alternative.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime