Question

I want to execute javascript code inside of an iframe as soon as the rendering begins, not when the document is loaded. The purpose is that i want to modify javascript behavior inside of the frame that is executed inside of an inline script block. The onload-event would execute after the inline script which would be too late. How to execute javascript as soon as the html starts to load?

Was it helpful?

Solution

You can't alter anything inside of an iframe which is not in your domain, assuming you are trying to get rid of the javascript code in the yahoo iframe from your other post.

OTHER TIPS

Instead of putting the code in onload, just place it in the script. For example, instead of

<script>
  function doStuff(){
    // ...
  }
</script>
<!-- snip -->
<body onload="doStuff();">

you should just do this:

<script>
  function doStuff(){
    // ...
  }
  doStuff();
</script>
<!-- snip -->
<body>

You can put the script inline, but be very careful with this. If the page is not fully loaded and you attempt to access the DOM, you could run into exceptions. In general, I don't really recommend that you inline script. It's better to control the execution flow yourself rather than rely on the behaviour of the browser. If possible, it might be better to look for ways to move your inline script into functions that allow you to sequence the calls.

Onload will not work for you in this case. If those pages are you own, you can put a script inside the header of each page, checking if the current window is a parent window or not. If its not a parent window, it implies its an iframe. Execute the code if its an iframe.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top