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).