IE executes inline scripts before external in dynamic iframe content

on a website I am writing the content of a dynamically added iframe with JavaScript. After the content is added 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 come before internal scripts . This is very strange since the normal process is for JavaScript to load synchronously step by step.

Example:

My web page:

<!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 the status of the example to see which type of log gets executed first:

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 outside, even if the outside was added to the iframe before!

Can someone tell me why and how to avoid it?

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

+3


source to share





All Articles