Sometimes, you need to put your content into a "cage" yet you don't what to go through the expanse of having a full iframe load. (this is very expensive, kind of like opening new page) and you get into all kinds of cross domain issues, so your inner frame content cannot talk to the parent frame.
Well the good news is that there is a trick for that. You can create an iframe as an element, and document.write() the content into it, without going through the expanse of opening a new page.
Here is what the code would look like (in jQuery) syntax:
// Create iframe. var iframe = $('<iframe />'); // Add it to the dom. $("#targetDiv").append(iframe); // Find the iframe in the DOM. var iWindow = iframe.contentWindow; // Get the iframe document. var iDoc = iWindow.document, // Write the content "string" into the iframe. iDoc.open(); iDoc.write("Hello world!"); iDoc.close();
The "iDoc.close()" part of the code is little tricky in firefox, so I ended up doing some kind of callback to check when the iframe finished loading, and then do the "iDoc.close()". But that part of the code was little messy, so I leave it out for now.
What can this be used for? All kinds of little hacks and trick, especially when dealing with cross-domain loading/sending. For example this is the base approach for doing cross-domain posts. Another one can be, if you are trying to dynamically load script tags that contain document.write() such as third party ads. Google uses similar approach in their gData API to do all server/client communication. I have not explored this one in depth yet, I but last time I was trying to find a source in the Facebook iframe app API, I did not see one...