首页 > js这几种动态添加的请求是都会发出吗?

js这几种动态添加的请求是都会发出吗?

一、动态添加iframe

var ifr = document.createElement('iframe');
ifr.id = 'test';
ifr.src = 'xxxxx';
ifr.style.display = 'none';
document.body.appendChild(ifr);

二、动态添加img

var img = new Image();
img.id = 'test';
img.src = 'xxxxx';
img.style.display = 'none';
document.body.appendChild(img);

三、动态添加script

document.write('<scri'+'pt src="xxx?t=' + Date.now() +'"></scri' + 'pt>'

以上这几种动态添加的请求,好像并不是100%执行


除了第二个,其他的两个应该都是每次都会发请求的.

第二个, 当你添加的这个图片在当前页面被入过(且服务器端没有告知浏览器不允许缓存该文件)的话, 应该是不会发请求的.


回复 @公子 的疑问(请注意,我是有选中 禁用缓存 这个功能的):

测试代码:

var runTime = 0;
setInterval(function(){
    var img = new Image();
    img.src = 'https://sfault-avatar.b0.upaiyun.com/187/042/1870427853-1030000000334890_big64';
    document.body.appendChild(img);
    img = null;
    console.log(++runTime, new Date().toLocaleString());
}, 3000);

代码执行的时候浏览器没有请求发出是因为我当前的这个测试页面已经加载了我的这个图片.

另外条件有限,我就不测试那个 Cache-Control: no-store 的那个情况了.

Cache-Control: no-store 的测试结果:

测试代码:
1.html

<body>
<img src="t.php/123.png" />

<script type="text/javascript">
if(console && console.log){
    var runTime = 0;

    setInterval(function(){
        var img = new Image();
        img.src = 't.php/123.png';
        document.body.appendChild(img);
        img = null;
        console.log(++runTime, new Date().toLocaleString());
    }, 3000);
}
</script>
</body>

t.php

<?php
header('Cache-Control: no-store');
header('Content-Type: image/png');
echo readfile('t.png');

png的图片我就不提供了,如果需要做测试,自己随便找一张就可以了.

【热门文章】
【热门文章】