Properly cleaning up a JQuery Dialog box to prevent memory leaks

One of the cool things about JQuery is you can declare an invisible DIV with a “display:none” style and then use that DIV as the content for a popup dialog box in your application. I have been working on a pretty dynamic web application that is pretty much all JavaScript and buttons come and go based on the users actions. This can present a problem with regard to memory consumption. Each time you call $(“#dialog”).dialog() jQuery creates a set of DIV’s in the base of the HTML.

Let’s take this dialog for example:

jquery-dialog-pic

The source code for this dialog is this:

jquery-dialog-code

These jQuery created DIV’s can get very large if you are not careful, essentially this code below will get created each time and will be larger depending how much HTML is in the original DIV block:

jquery-dialog

That is a very basic dialog so you can imagine what it might look like over time. Here is Google Chrome’s developer panel of a dialog box that was opened 5 times without proper cleanup (I highlighted the first occurrence in blue):

chrome-jquery-dialog

So, what is the solution? It is actually very simple!

$("#dialog").dialog({ 
 closeOnEscape: true,
 show: "slow", 
 model: true, 
 minWidth: 600,
 close: function( event, ui ) {
    ...Do some cool stuff on close

    //Now call "destroy"
    $("#dialog").dialog("destroy");
 }
 });

If you run in Google Chrome and switch to the Elements tab you will actually see the JQuery created DIV’s come and go as the dialog is opened and then closed.

 

Short URL: http://bit.ly/YhHi9o