Sunday, March 16, 2008

Mozilla firefox: dynamicaly load javascript file in browser

Played with JavaScript concepts;

Tried to load JavaScript dynamically for the execution.
DOM solution was:


var scr = document.getElementById("ctl-file").value;
document.getElementById("current_ctl").innerHTML=scr;
var s=document.createElement("script");
s.setAttribute("type","text/javascript");
s.setAttribute("src", scr);
var bodyID = document.getElementsByTagName("body")[0];
bodyID.appendChild(s);
def_vars(); // <- this defined inside of document;
// it does not work in Mozilla


It loads to dom, but not executes.

Another proposed solutions are using framewoks (big, and I suppose that's why buggy, XMLHttpRequest (? no idea how it can solve problem)).

I have tried to use IFRAME tag, and implemented workaround based on this tag.

The working code for Mozilla is:


..
<iframe id="schema_exec"
src ="basic.js"
width="100%">
</iframe>
..
var scr = document.getElementById("ctl-file").value;
document.getElementById("current_ctl").innerHTML=scr;
document.getElementById("schema_exec").setAttribute("src", scr);
// previous command substituted basic.js by our file
code_for=document.getElementById("schema_exec").contentDocument.body.textContent;
eval(code_for);

No comments: