I’m just testing out replacing a whole page with another page using JavaScript and I found this answer with document.write. As to why document.write, I needed to replace the entire HTML, including scripts and styles using the same page.
It does what I want but i can’t seem to have consistency with my event handlers. My handlers are all attached to document using:
$(document).delegate(...);
Currently, I have weird results. In a fiddle I made, it attaches a handler. When clicked, the event fires, rewrites the page, runs the function again – but it doesn’t attach the handler.
However in my project, I’m doing the same routine (d.w(), then add handlers). It does reattach once and handlers work, but after doing a second routine (still on the same page), it doesn’t attach anymore.
So my questions are:
- When using
d.w(), do existing handlers get erased fromdocument? - Are
windowas well asdocumentthe same after subsequentd.w()s? or are they somehow “renewed” - Do scripts that are already parsed stay in memory and run after subsequent
d.w()s? Or do they get erased as well?
(The following applies to google chrome)
Only the
documentis cleared, the scripts in memory still stay the same. You can easily test it by setting something to a variable and see if it exists after clearing out the document with.open.The old native handler is therefore lost from the document, but jQuery still thinks that the handler exists in its own event model. You can see it by editing the log to:
jQuery only ever attaches a single native handler per event, so if you have a
"click"event registered ondocument, further handlers attached with jQuery don’t attach a new native handler, instead the handler is pushed into the jQuery internal handlers array.Now, because
document.openremoved the native handler, but doesn’t clear javascript, jQuery still thinks the native handler exists, and further.delegateonly goes to the jQuery internal handler array. If you replace your handler with plain olddocument.onclickyou will see it starts working.You can also keep using jQuery if you add
$(document).unbind()(or more robust$.cache = {};, but this is internal and subject to change) before the.delegate, so that jQuery is again synced. Otherwise it won’t be, since it has no idea you calleddocument.open.So:
documentafter a.openhttp://jsfiddle.net/wphzt/4/