5

前端开发时使用iframe标签的时候发生两次请求问题的解决方法

 3 years ago
source link: https://blog.csdn.net/m54584mnkj/article/details/112602348
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

前端开发时使用iframe标签的时候发生两次请求问题的解决方法

使用iframe可以加载其他页面的元素,比较方便,但是在实际运用中,
在某些浏览器中或发生某种行为时会出现加载两次或多次请求的问题,导致资源浪费.
正常使用时如下方这种情况:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <iframe src="demo0.html" frameborder="0"></iframe>
    <button class="btn">按钮</button>
</body>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
<script>
    var num = 0
    $(".btn").click(function () {
        num++;
        $("iframe").attr("src", "demo" + num + ".html")
    })
</script>
</html>

这样我们会发现每次点击都会只触发一次报错,那证明了其实每次只触发了一次,这样是正常的.

在这里插入图片描述

当我们切换下面的写法时,会出现不同的情况.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <iframe src="demo0.html" frameborder="0"></iframe>
    <button class="btn">按钮</button>
    <div class="box">

    </div>
</body>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
<script>
    var num = 0
    $(".btn").click(function () {
        num++;
        $(".box").html($("iframe").attr("src", num))
    })
</script>

</html>

运行这段代码会发现每次点击的时候都会产生两次报错。
在这里插入图片描述

分析原因:
这样我们会发现会触发两次报错,这是为什么?
经过调查发现,在JS生成src的时候,是可以正常调用一次请求的,
在实际开发时,我们通常会把iframe标签做成弹框的形式来展现,这样在做弹框的时候,就会对生成后的iframe标签进行移动,生成iframe标签之后,对dom元素移动之后就会产生两次请求.说明移动
dom元素会再一次触发iframe标签触发请求.
这两次请求分别为:
一次是在加载时生成dom元素时发送的请求,
另一次是移动dom元素时发送的请求.

解决方法:
第一种方法
不要在js生成时候在进行dom元素的移动,而是通过js生成dom元素.

<script>
    var num = 0
    $(".btn").click(function () {
        num++;

        $(".box").html("<iframe src=" + num + "></iframe>")
    })
</script>

第二种方法
每次生成dom元素的时候,清空之前的iframe标签,一定意义上就是说去除了iframe的请求

<script>
    var num = 0
    $(".btn").click(function () {
        num++;
        $(".box").empty();
        $(".box").html($("iframe").clone().attr("src", num))
    })
</script>

通过这两种方法,再看就发现发次只会进行一次请求了。

在这里插入图片描述
在这里插入图片描述

以上就是对前端开发时使用iframe标签的时候发生两次请求问题的解决方法,欢迎大家讨论交流。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK