我需要将 SCRIPT 添加到沙盒 IFRAME 中,并且我试图避免使用document.write
(see here https://stackoverflow.com/questions/4537963/what-are-alternatives-to-document-write and here https://stackoverflow.com/questions/802854/why-is-document-write-considered-a-bad-practice)但是 DOM 版本没有按顺序执行脚本。在下面的示例中,在内联脚本执行时 jQuery 尚未加载,而document.write
版本首先加载 jQuery,然后执行内联脚本。
出于我的目的(确保在运行内联脚本之前加载所有主要库,请参阅here http://www.stevesouders.com/blog/2012/04/10/dont-docwrite-scripts/) document.write
可能是正确的方法(但 DOM 更好,只是没有按应有的方式工作),但我更愿意在可能的情况下允许异步下载,同时确保脚本标记按顺序执行。
我有一种感觉,DOM 方法确保了顺序src
ed SCRIPT 标签,但不是内联标签...但是如果有人可以帮助我获得一个与 DOM 一起使用的版本,以预期的顺序执行脚本,那就太好了!
另外...谁能向我解释一下为什么insertAdjacentHTML
版本根本不起作用!?
<html>
<head>
<title>Testing DOM -vs- document.write Script additions...</title>
<script>
var $sandboxWin,
$jQuery = document.createElement('script'),
$script = document.createElement('script'),
$head = document.head,
sType = "insert"
;
$head.insertAdjacentHTML('afterbegin', '<iframe id="neek" style="display:none;" sandbox="allow-scripts allow-same-origin"></iframe>');
$sandboxWin = document.getElementById("neek").contentWindow;
switch (sType) {
case "dom": {
$jQuery.type = "text/javascript";
$jQuery.src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js";
$sandboxWin.document.head.appendChild($jQuery);
$script.type = "text/javascript";
$script.text = "console.log('via appendChild:'); console.log($);"; //.innerHTML
$sandboxWin.document.head.appendChild($script);
break;
}
case "insert": {
$sandboxWin.document.head.insertAdjacentHTML('afterbegin', "<script src='jquery.min.js'><\/script>");
$sandboxWin.document.head.insertAdjacentHTML('afterbegin', "<script>console.log('via insertAdjacentHTML:'); console.log($);<\/script>");
break;
}
default : {
$sandboxWin.document.write(
"<script src='jquery.min.js'><\/script>" +
"<script>" +
"console.log('via document.write:'); console.log($);" +
"<\/script>"
);
$sandboxWin.document.close();
}
}
</script>
</head>
<body>
Testing DOM -vs- document.write Script additions...
</body>
</html>
None
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)