The Problem:
I have a javascript file that uses document.write to send output to the browser. This javascript file contains some html code and another script tag.
The execution order in Internet Explorer (6&7) appears to be different than that of browsers such as FireFox.
Example:
myjs.js
Expand|Select|Wrap|Line Numbers
- var output = '<ul><li id=\"myli\"><scr'+'ipt type=\"text/javascript\" src=\"3rdparty.js\"></scr'+'ipt></li></ul>';
- document.write(output);
Expand|Select|Wrap|Line Numbers
- document.write('3rd party output');
<ul><li>3rd party output</li></ul>
Internet Explorer:
<ul><li></li></ul>3rd party output
Experimenting:
I don't have control over the content / output of the 3rdparty.js file, and the html code in the output var always arrives as a string (although it can be processed server-side using php if need be).
I therefore did a bit of reading up on DOM functions such as appendChild, and tried to combine it with usage of innerHTML to include the html string in a div, then execute the script tag.
myjs.js (amended)
Expand|Select|Wrap|Line Numbers
- function scripts(id) {
- var el = document.getElementById(id).getElementsByTagName("script");
- var limit = el.length;
- for(var x=0; x < limit; x++) {
- newScript = document.createElement("script");
- newScript.type = "text/javascript";
- if(el[x].text != "") {
- newScript.text = el[x].text;
- } else {
- newScript.src = el[x].src;
- }
- document.getElementById(id).innerHTML = "";
- document.getElementById(id).appendChild(newScript);
- }
- }
- var div = '<div id=\"mydiv\"></div>';
- var output = '<ul><li id=\"myli\"><scr'+'ipt type=\"text/javascript\" src=\"3rdparty.js\"></scr'+'ipt></li></ul>';
- document.write(div);
- var el = document.getElementById('mydiv');
- el.innerHTML = output;
- scripts('myli');
If anyone else with a greater understanding of javascript could point me in the right direction, I'd really appreciate it.