【问题标题】:use javascript to write a random <script>使用 javascript 编写一个随机的 <script>
【发布时间】:2019-03-18 06:04:49
【问题描述】:

如何将 4 个预定义 &lt;script&gt;s 中的随机 1 个添加到网页?

即第三方工具有 4 个电子书下载模式表单,由唯一的 &lt;script&gt; 生成(每本电子书 1 个)。

我想在页面中随机添加1个&lt;script&gt;s,这样在每次页面加载时,都会显示不同的电子书下载模态表单。

我该怎么做?

我试过了:

var min=1; 
var max=4;  
var random = Math.random() * (+max - +min) + +min; 

switch ($random) {
   case 1:
       document.write(<script src=""></script>)
   break;

但是document.write 中的&lt;/script&gt; 关闭了主要的&lt;script&gt;。我需要为&lt;&gt; 使用HTML ascii 代码吗?

帮助表示赞赏。

更新

我需要添加的脚本格式为:

<script type='text/javascript' async='true' src='https://app.ontraport.com/js/ontraport/opt_assets/drivers/opf.js' data-opf-uid='p2c187780f17' data-opf-params='borderColor=#ec0c8d&borderSize=5px&formHeight=572&formWidth=60%&maxTriggers=2&onExitIntent=true&popPosition=mc&timeframe=1&instance=1067093054'></script>

【问题讨论】:

  • 好吧,作为一种更好、更简洁的解决方案,您可以在每个页面上使用一个相同的脚本,在电子书上使用随机链接,而不是 4 个随机脚本
  • 您可以只使用'&lt;\/script&gt;' 来避免关闭脚本标签。但更好的解决方案根本不会使用document.write

标签: javascript random


【解决方案1】:

您可以随机选择预定义脚本src URL,然后为其动态添加script 标签:

// List of possible attributes that script element could get
var scripts = [
    { src: "http://abc/scr1.js", "data-opf-uid": "23", "data-opf-params": "y='a'" },
    { src: "http://abs/scr2.js", "data-opf-uid": "81", "data-opf-params": "x=9" }
];
// Select a random entry from above list
var selected = scripts[Math.floor(Math.random()*scripts.length)];
selected.type='text/javascript';
// Create the script DOM element
var script = document.createElement('script');
// Assign the selected properties to the element as attributes
for (var prop in selected) {
    script.setAttribute(prop, selected[prop]);
}
// Add the element to the document
document.head.appendChild(script);

将此作为script 放入文档的body 部分。

如果远程脚本设计为在body标签中加载,那么最后一行应改为:

document.body.appendChild(script);

您在上述scripts 对象中定义的属性不需要任何HTML 转义:当使用setAttribute() 将这些属性添加到生成的script 元素时会处理这些转义。您提到您的脚本需要 async 属性,但这与通过代码添加的脚本无关:它们无论如何都是异步的。所以不需要(但也没有害处)添加这些。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-27
    • 2023-03-04
    • 1970-01-01
    相关资源
    最近更新 更多