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:


The source code for this dialog is this:


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:


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):


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

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

    //Now call "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.


10 thoughts on “Properly cleaning up a JQuery Dialog box to prevent memory leaks

  1. How coincidental…

    I JUST finished doing the exact same thing. My dialogs are created dynamically however, based on a document unid, so I am appending a div to the body before I init the dialog. In the close function, I also do a .remove() on the div I added as an extra cleanup step.

  2. Additionally, if you are adding a div element to a page dynamically and then turning it into a dialog, you can do a .remove() on the div element after destroying the dialog.

    • Another good tip Alan! I make sure I call remove also. Cleaning up is critical is dynamic applications, I should have also written about doing an unbind on the click event handlers. For a bit there I was getting 2, 3, 4 clicks per single click because I wasn’t calling unbind properly.


      • Hi Bob, I’m having the same problem (sporadically) of getting 2,3,4 clicks per single click when I open the dialog. where would you put the ‘$(“selelctor”).unbind(“click”)’ in the dialog? In the Open options? Thanks.

  3. The .destroy() method, same goes for dojo. We have an app where we use dojo widgets extensively (content panes, tree grids, grids, dialogs, spinners, etc.) and users log in and use for 8hr shifts. We learned the hard way, but if we don’t destroy widgets, we run into memory problems.

  4. Pingback: Thank you for a great 2015 and Happy New Year! | Bob's Blog

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.