@Phaedra

I trust you are not a beginner but here we see a jQuery beginners
code ;o)
If I may "intsruct" you ? Ok.

Number one source of confusion and "leaks" or leaks is repeated
calling of $() function.

$("<div id='container'/>").appendTo("body");

First div html markup above is not 100% ok, and this kind of html is
deliberately not going to be handled properly by jQuery. Only *legal*
html is guaranteed to "work".
Second. Above is *much* more efficient and much less damaging when
changed to this:

var $body = $(document.body) ;
// in a loop
$body.append("<div class='container' ></div>")

Please note te two things about html markup here
1.
div is properly closed
2.
different div with the same id are not forced into the browser.

IMPORTANT: allways have as less as possible jQuery instances ! call to
$() is expensive.

Your second example is even worse ... ;o(

function update() {  $("#clock").html(new Date()); }
window.setInterval(update, 500);

Basically here we have $() being called every 500 microseconds ?! And
again not vey legal html ... The proper way of doing the above might
be this :

var  $clock = $("#clock") ;
function update() {  $clock.text(new Date()); }   // no html just text
var timer_id = window.setInterval(update, 500);
// help IE to release memory ASAP
$(document).unload(function() {
         window.clearInterval( timer_id ) ; timer_id = null ;
         $clock = null ;
}) ;


Summary

Good programming principles apply to jQuery adorned code too.
Especially in "single page" apps.
Last but not the least. people have investigated and developed
solutions for long-lived single page apps.
Here are the two I regularly use:

jQuery.fn.flush = function()
/// <summary>
/// $().flush() re-makes the current element stack inside $()
/// thus flushing-out the non-referenced elements
/// left inside after numerous remove's, append's etc ...
/// </summary>
{ return jQuery(this.context).find(this.selector); }

// http: //townx.org/blog/elliot/memory-leaks-and-jquery
$(document).unload(function() { $('*').unbind(); });

Happy jQuerying ;o)

--DBJ

Reply via email to