<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>top</title>
<link rel="stylesheet" href="">
<style>
.iframe {
width: 400px;
height: 400px;
border: 1px solid #f00;
}
</style>
</head>
<body>
<div>
这是top
</div>
<iframe class="iframe" id="iframe" frameborder="0"></iframe>
<script>
var iframe = document.getElementById('iframe');
// iframe.contentWindow.document.open();
iframe.contentWindow.document.write(`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>demo预览</title>
<style>
.div {
height: 100px;
width: 100px;
background: #f60;
}
<\/style>
</head>
<body>
<div class="div">123</div>
<script src="jquery-1.12.4.min.js"><\/script>
<script>
console.log(111);
$(function(){
console.log(222);
})
window.onload = function() {
console.log('onload');
}
console.log($('.div').text());
console.log(333);
<\/script>
</body>
</html>`)
// iframe.contentWindow.document.close();
iframe.onload = function() {
console.log('iframe is loaded')
}
</script>
</body>
</html>
关于 iframe.contentWindow.document.open();
和 iframe.contentWindow.document.close();
不使用:
![](https://img.haomeiwen.com/i2348301/c53c1a9459de0004.png)
使用后:
![](https://img.haomeiwen.com/i2348301/8a926905eef504f6.png)
可以看到原本 iframe
中的 onload
事件和 $(function() {})
都没有触发,切父页面中 onload
事件也没有触发。
如果没有使用 document.close
,则浏览器一直在加载状态,如下图所示
![](https://img.haomeiwen.com/i2348301/3a3dcf5e4b4f7347.png)
![](https://img.haomeiwen.com/i2348301/04b6e3b2398e36b2.png)
网友评论