Background: I need to load ad scripts after the DOM has loaded. Because many of the scripts use docume开发者_Go百科nt.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: Why does appending a <script> to a dynamically created <iframe> seem to run the script in the parent page?. 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.
IE needs defer="true"
in the script tag when it should execute dynamically.
In case no one else has any better ideas, I did discover one solution, albeit a non-ideal one.
As per Michael Kleber's very useful comment here: Why won't this JavaScript (using document.open and document.write) work in Internet Explorer or Opera?, calling
document.close()
will hang all script execution in IE. Simply omitting that line makes the script execute. I would prefer a solution that doesn't involve leaving the iframe document open, as I don't know what kind of consequences that might entail.
精彩评论