0%

Vue中插入脚本

当你拿到的广告代码是包含script标签时,则需要通过一定的转换,才能正常渲染到页面上。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
//当你拿到的广告代码如下:
<script type="text/javascript">
atOptions = {
'key' : '1523b7ddb936e560aadef64a851d500c',
'format' : 'iframe',
'height' : 250,
'width' : 300,
'params' : {}
};
</script>
<script type="text/javascript" src="//www.highperformanceformat.com/1523b7ddb936e560aadef64a851d500c/invoke.js"></script>


//转换后:
const targetDiv = document.getElementById("de_v");
if (!targetDiv) return;

// 创建第一个 script 设置 atOptions
const script1 = document.createElement("script");
script1.type = "text/javascript";
script1.innerHTML = `
atOptions = {
'key' : '1523b7ddb936e560aadef64a851d500c',
'format' : 'iframe',
'height' : 250,
'width' : 300,
'params' : {}
};
`;

// 创建第二个 script 负责加载外部 JS
const script2 = document.createElement("script");
script2.type = "text/javascript";
script2.src = "//www.highperformanceformat.com/1523b7ddb936e560aadef64a851d500c/invoke.js";

// 插入到 #de_v 容器内
targetDiv.appendChild(script1);
targetDiv.appendChild(script2);
-------------本文结束感谢您的阅读-------------