0

I've created an iframe using javascript:

fr=document.createElement('iframe');
fr.src="www.example.com";
fr.onload=doSomething();
document.body.appendChild(fr);

problem is the onload part seems to be running before the iframe loads - I get an error in the console (using chrome) about something undefined in the function (and it would be defined once the iframe loads), and when I check, it turns out the iframe was never even appended.

user1999728
  • 913
  • 1
  • 8
  • 25
  • 4
    That’s because you are _calling_ the function, instead of just assigning the reference to it – `fr.onload=doSomething;` is what you want there. – CBroe Jan 23 '15 at 17:44
  • @CBroe Thank you (and Travis. Can't accept his answer yet) – user1999728 Jan 23 '15 at 17:48

1 Answers1

4

onload expects a function reference to call

fr.onload=doSomething;

When you assign doSomething() to the onload event handler, its return is called (which is undefined) and that is the error you see. This is also the reason why doSomething appears to run immediately (because it executes during the assignment).

Travis J
  • 81,153
  • 41
  • 202
  • 273