I’ve been struggling all day with the document.write and the onLoad function.
If you consider a JS code like this one =>
window.i = 0;
console.log(i + " //should be 0");
document.write("<scr"+"ipt onLoad='onA1Ready()' src='a1.js'><\/sc"+"ript>");
function onA1Ready(){
document.write("<scr"+"ipt onLoad='onA2Ready()' src='a2.js'><\/sc"+"ript>");
}
function onA2Ready(){
console.log(i + " //should be 2");
}
and a1.js beeing like this =>
i++;
console.log(i + " //should be 1");
and a2.js beeing quite similar =>
i++;
console.log(i + " //should be 2");
I’d expect the last console output to be equal to 2, but instead here is what I get out of the console =>
0 //should be 0 test.js (line 2)
1 //should be 1 a1.js (line 2)
i is not defined ERROR i++; a2.js (line 1)
onA2Ready is not defined
I guess this issue is scope related, but I can’t figure how.
It would be great if any of you had an idea of what’s going on here.
I tested on Chrome 16 and everything ran as expected. However, in the latest FF I got the error you described.
My advice is to stop using the evil
document.write()to dynamically load scripts. Instead use DOM methods. I have written a little functionmyLoader()that can help youTry it out.
The output I get