IE executes inline scripts before external in dynamic iframe content

倖福魔咒の 提交于 2019-12-23 20:36:19

问题


within a website I'm writing the content of a dynamically added iframe with JavaScript. After adding the content to the iframe the JavaScript in the iframe will be executed. Unfortunately there are differences in IE. IE (8-11) will execute inline JavaScript first, before executing external scripts even if they are before the internal scripts. This is very strange since the normal process is, that JavaScript will be loaded synchronously step by step.

Example:

My webpage:

<!DOCTYPE html SYSTEM "about:legacy-compat">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=8" />
        <meta charset="UTF-8">
        <title>
            TEST
        </title>
    </head>
    <body>
        <iframe name="testFrame" frameborder="0"></iframe>
        <script type="text/javascript" src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function(){
                var $iframe = $("iframe");

                // Data
                var data = "<!doctype html><html><head>";
                data += '<scrip'+'t type="text/javascript" src="test1.js"><'+'/script>';
                data += '<scrip'+'t type="text/javascript">console.log("Inline");<'+'/script>';
                data += "</head><body>TEST</body></html>";

                // Write in frame
                var dstFrame = $iframe[0];
                var dstDoc = dstFrame.contentDocument || dstFrame.contentWindow.document;
                dstDoc.write(data);
                dstDoc.close();
            });
        </script>
    </body>
</html>

test1.js will just log a example status to see what kind of log will be executed firstly:

console.log("EXTERNAL");

In Firefox the console will be:

"EXTERNAL" test1.js:1
"Inline" test.html:1
"EXTERNAL" test1.js:1
"Inline" test.html:1

In IE the console will be:

EXTERNAL
Inline
Inline
EXTERNAL

As you can see the inline content will be executed before the external even if the external was added to the iframe before!

Can somebody tell me why and how to avoid it?

Notice: You can ignore the first two console logs since the parser will log the JavaScript even if it is inside a string (in my example it is inside the string).

来源:https://stackoverflow.com/questions/27411562/ie-executes-inline-scripts-before-external-in-dynamic-iframe-content

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!