What if you rendered the #template HTML in a hidden div and instead of writing HTML to the #content onbeforeunload, you just show/hide the unload content you wish to display?
I suspect that since the browser is essentially locked, it can't do the async writing like images that it needs to do. If you show/hide, this async writing will already be done.
Just a guess but I think that will work?
EDIT: Oops. I assumed your 'dont leave' notificaton was an alert, which would lock. I realize now that that's not what you're doing, so ignore that bit :)