0

I have a SPA ( single page application ) programmed in HTML/JavaScript/JQuery/CSS

Every time a navigation link is clicked the main div is loaded with a chunk of HTML/JavaScript/JQuery/CSS via the ajax command and the getScript function is used to load the JavaScript/JQuery portion of that chunk.

Once a user clicks on another link, the main div is removed via the remove() function and the new chunk with its JavaScript/Jquery replaces it.

HERE'S THE PROBLEM: when I load the content of the main div for the second, third, etc. time ( if a user clicks on another link but then comes back to this one ) do I run the getScript function again to load the JavaScript/JQuery? If so - wouldn't it bind the "on" and other events over each other, or does the remove() function take care of it and it's safe to do without any memory leak?

Thank you for your responses!

kidalex
  • 1,437
  • 2
  • 12
  • 14

1 Answers1

0

From http://api.jquery.com/remove/

Similar to .empty(), the .remove() method takes elements out of the DOM. Use .remove() when you want to remove the element itself, as well as everything inside it. In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed. To remove the elements without removing data and events, use .detach() instead.

So all events bound on the div and its descendants will be removed and can be safely rebound. However if the JavaScript you are injecting binds events to things outside the div like the document, window, body etc.. multiple events will be bound which will likely cause problems if unintended.

As of jQuery 1.4, the same event handler can be bound to an element multiple times. This is especially useful when the event.data feature is being used, or when other unique data resides in a closure around the event handler function.

http://api.jquery.com/on/

If you absolutely must bind to higher level elements from the script that is run repeatedly then you should look in to using off() before you bind the events.

kaan_a
  • 3,503
  • 1
  • 28
  • 52
  • I only bind using "on" and only to a specific selector and never to a body or html element – kidalex Aug 15 '13 at 00:12
  • Well if your selector is within what gets removed you are safe. You could maybe get a bit of a performance boost by hiding and showing the last n divs instead of removing them, but I doubt it's worth the effort. – kaan_a Aug 15 '13 at 00:21