How can I append and execute a script inside an iframe in a cross browser way (specifically IE!)?
- by agmin
Background: I need to load ad scripts after the DOM has loaded. Because many of the scripts use document.write() and other potentially bad functions to run after the DOM has loaded, I want to load the scripts inside an iframe.
So when the ad needs to be shown, an event is triggered which does the following:
var iframe = document.createElement('iframe');
iframe.setAttribute('id', 'iframeId');
iframe.setAttribute('src', 'about:blank');
var adContainer = document.getElementById('AdContainer');
adContainer.appendChild(iframe);
var val = '<html><head></head><body>';
val += '<scr' + 'ipt type="text/javascript" src="' + url + '"></scr' + 'ipt>';
val += '</body></html>';
If I don't assign the html and body tags to val, the script automatically gets appended to the head of the iframe and fails to execute in FF. In IE, the script doesn't execute with or without the head/body/html tags.
var doc = iframe.contentWindow || iframe.contentDocument;
if (doc.document){
doc = doc.document
}
doc.open();
doc.write(val);
doc.close();
I found this last bit of code here: http://stackoverflow.com/questions/1591135/why-does-appending-a-script-to-a-dynamically-created-iframe-seem-to-run-the-s. I do NOT want to load jquery in the iframe though, I just want to append a script and have it execute.
My current solution seems to work great in FF and Webkit. However, IE doesn't execute the script. The script is written to the page, but doesn't start running. Is there a better way to append the script to the iframe so it will run cross browser? Or is it possible to tell IE to run the script?
I know that I could load an external document with the ad script via the iframe, but I don't want to make the extra call to my server if I can do this dynamically. Also, I've tried using appendChild() on the iframe's body to insert the script, but since the script element is created outside the iframe's DOM this doesn't seem to work.