Javascript execution access points in a document

2019-07-25 15:42发布

问题:

I'm wondering, where the script interpretation starts in a document with an iframe, that contains another document, with "<header><script>" or possibly "<body><script>". I just really need to ensure that the execution happens in the "outer" document before the iframe document, but it seems that it is random, is that right ?

BTW, what about the order of interpretation of referenced javascripts ? Does it depend on "where" in the document I reference it ?

回答1:

I just really need to ensure that the execution happens in the "outer" document before the iframe document

To do this with 100% certainty, you would have to create the iframe in the outer document's DOMReady event (e.g. with jQuery's .ready()). If you embed it directly into the document, there is indeed no guarantee of when the scripts will execute.

what about the order of interpretation of referenced javascripts ? Does it depend on "where" in the document I reference it ?

Yes, script blocks get executed in the order they are in the page. Here is a great answer on the issue: Load and execution sequence of a web page?



回答2:

It really depends how you inject the Javascript (in the parent document and the <iframe>) and where you inject it.

If for instance, you use dynamic script insertion in your parent document, but blocking <script> tags in your iframe code, the iframe script will probably get executed first.

The pitfall can be if you put your <script> tags at the bottom of your parent document but the <iframe> somewhere above.

So in general, if you use blocking <script> tags before you actually create the <iframe> in your parent document, this "should" execute first. But then again cutting edge browser will try to load those scripts in parallel mode which also could lead to a wrong behavior there.

You should create the <iframe> dynamically on the DOMContentLoaded or onload window event in your parent document.